用Pexpect与SSH交互(实现了参数化输入以及命令行shell交互的形式)

#!/usr/bin/python  
#coding=utf-8  
import pexpect  
from optparse import OptionParser  
  
#SSH连接成功时的命令行交互窗口中的提示符的集合  
PROMPT = ['# ','>>> ','> ','\$ ']  
  
def send_command(child,cmd):  
    #发送一条命令  
    child.sendline(cmd)  
  
    #期望有命令行提示字符出现  
    child.expect(PROMPT)  
  
    #将之前的内容都输出  
    print child.before.split('\n')[1]  
  
def connect(user,host,password):  
    #表示主机已使用一个新的公钥的消息  
    ssh_newkey = 'Are you sure you want to continue connecting'  
    connStr = 'ssh ' + user + '@' + host  
  
    #为ssh命令生成一个spawn类的对象  
    child = pexpect.spawn(connStr)  
  
    #期望有ssh_newkey字符、提示输入密码的字符出现,否则超时  
    ret = child.expect([pexpect.TIMEOUT,ssh_newkey,'[P|p]assword: '])  
  
    #匹配到超时TIMEOUT  
    if ret == 0:  
        print '[-] Error Connecting'  
        return  
  
    #匹配到ssh_newkey  
    if ret == 1:  
        #发送yes回应ssh_newkey并期望提示输入密码的字符出现  
        child.sendline('yes')  
        ret = child.expect([pexpect.TIMEOUT,ssh_newkey,'[P|p]assword: '])  
  
    #匹配到超时TIMEOUT  
    if ret == 0:  
        print '[-] Error Connecting'  
        return  
  
    #发送密码  
    child.sendline(password)  
    child.expect(PROMPT)      
    return child  
  
def main():  
    parser = OptionParser("[*] Usage : ./sshCommand2.py -H <target host> -u <username> -p <password>")  
    parser.add_option('-H',dest='host',type='string',help='specify target host')  
    parser.add_option('-u',dest='username',type='string',help='target username')  
    parser.add_option('-p',dest='password',type='string',help='target password')  
    (options,args) = parser.parse_args()  
  
    if (options.host == None) | (options.username == None) | (options.password == None):  
        print parser.usage  
        exit(0)  
  
    child=connect(options.username,options.host,options.password)  
      
    while True:  
        command = raw_input('<SSH> ')  
        send_command(child,command)  
  
if __name__ == '__main__':  
    main()  



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值