python—pexpect的pxssh进行模拟ssh登陆返回相关命令信息
pxssh 是 pexpect 中 spawn 类的子类,增加了login()、logout()和prompt()几个方法,使用其可以轻松实现 ssh 连接,而不用自己调用相对复杂的 pexpect 的方法来实现。
prompt(self,timeout=20)方法用于匹配新提示符
使用pxssh替代上一小节的脚本:
一开始遇到一个问题,就是直接按书上的敲import pxssh会显示出错,但是明明已经安装了这个文件,查看资料发现是pxssh是在pexpect包中的,所以将其改为from pexpect import pxssh就可以了。
运行结果:
1、前提
本机客户端192.168.100.139
远程ssh服务器192.168.100.140
在本机客户端192.168.100.139可以ssh命令登陆服务器192.168.100.140
root@kali:~/python/anquangongji#
root@kali:~/python/anquangongji# ssh [email protected]
root@192.168.100.140's password:
Linux kali 3.18.0-kali1-686-pae #1 SMP Debian 3.18.3-1~kali4 (2015-01-22) i686
The programs included with the Kali GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.
Kali GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Last login: Mon Dec 25 16:34:03 2017 from 192.168.100.139
root@kali:~# uname -a
Linux kali 3.18.0-kali1-686-pae #1 SMP Debian 3.18.3-1~kali4 (2015-01-22) i686 GNU/Linux
root@kali:~# exit
登出
Connection to 192.168.100.140 closed.
root@kali:~/python/anquangongji#
2、192.168.100.139本机脚本详情
root@kali:~/python/anquangongji# pwd
/root/python/anquangongji
root@kali:~/python/anquangongji# ls
checkfile.py dictionary.txt passwordunix.txt pexpectshhnocommand.py scanerftpbanner.py vulnbanners.txt
crarkpassword.py openfiletest.py pexpectcreaksshpassword.py pexpectshhusecommand.py scanmultports.py vulnftpbanner.txt
root@kali:~/python/anquangongji# cat pexpectcreaksshpassword.py
#!/usr/bin/python
#--*-- coding:utf-8 --*--
from pexpect import pxssh
def send_command(conn,cmd):
conn.sendline(cmd)
#匹配prompt(提示符)
conn.prompt()
#将prompt前所有的内容打印出
print conn.before
def connect(host,user,password):
try:
conn = pxssh.pxssh()
#利用pxssh类的login()方法进行ssh登录
conn.login(host,user,password)
return conn
except:
print "[---] Error Connecting!!!"
exit(0)
conn = connect("192.168.100.140","root","173605852")
send_command(conn,"uname -a")
root@kali:~/python/anquangongji#
3、运行情况
root@kali:~/python/anquangongji#
root@kali:~/python/anquangongji# python pexpectcreaksshpassword.py
uname -a
Linux kali 3.18.0-kali1-686-pae #1 SMP Debian 3.18.3-1~kali4 (2015-01-22) i686 GNU/Linux
root@kali:~/python/anquangongji#
4、192.168.100.139本机
root@kali:~/python/anquangongji# uname -a
Linux kali 4.0.0-kali1-686-pae #1 SMP Debian 4.0.4-1+kali2 (2015-06-03) i686 GNU/Linux
root@kali:~/python/anquangongji#
参考:http://blog.csdn.net/SKI_12/article/details/72972238?locationNum=2&fps=1