Python pexpec 解决scp ssh

本文介绍如何利用Python脚本结合SSH和SCP命令实现远程主机的命令执行及文件传输,包括处理SSH提示输入密码和确认连接的场景。

paswd_key = '.*assword.*'  匹配Password 

ssh_newkey = '.*(yes/no).*' 匹配 Are you sure you want to continue connecting (yes/no)

 

[python]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. #!/usr/bin/python2.7  
  2. import pexpect  
  3. import os, sys, getpass  
  4.   
  5.   
  6. def ssh_command(user, host, password, command):  
  7.     ssh_newkey = '.*(yes/no).*'  
  8.         passwd_key = '.*assword.*'  
  9.     child = pexpect.spawn('ssh -l %s %s %s' %(user, host, command))  
  10.     child.logfile = sys.stdout  
  11.     i = child.expect([pexpect.TIMEOUT, ssh_newkey, passwd_key])  
  12.   
  13.     if i == 0: #timeout  
  14.         print child.before  
  15.         print "Error time out"  
  16.         print child.after  
  17.         return None  
  18.     if i ==1 :  
  19.         child.sendline('yes')  
  20.         i = child.expect([pexpect.TIMEOUT, passwd_key])  
  21.         if i == 0:  
  22.             print child.before  
  23.             print 'time out ERROR'  
  24.             print child.after  
  25.             return None  
  26.     child.sendline(password)  
  27.     return child  
  28.   
  29.   
  30. def scp2(ip, user, passwd, dst_path, filename):  
  31.     passwd_key = '.*assword.*'  
  32.     if os.path.isdir(filename):   
  33.         cmdline = 'scp -r %s %s@%s:%s' % (filename, user, ip, dst_path)   
  34.     else:   
  35.         cmdline = 'scp %s %s@%s:%s' % (filename, user, ip, dst_path)   
  36.     try:  
  37.         child = pexpect.spawn(cmdline)  
  38.         child.expect(passwd_key)  
  39.         child.sendline(passwd)  
  40.         child.expect(pexpect.EOF)  
  41.         #child.interact()  
  42.         #child.read()  
  43.         #child.expect('$')  
  44.         print "uploading"   
  45.     except:  
  46.         print "upload faild!"  
  47.   
  48. def main():  
  49.     host = raw_input('Hostname:')  
  50.     user = raw_input('User:')  
  51.     password = getpass.getpass()  
  52.     command = raw_input('Command:')  
  53.     child = ssh_command(user, host, password, command)  
  54.     child.expect(pexpect.EOF)  
  55.     print child.before  
  56.   
  57. if __name__ == "__main__":  
  58.       
  59. main()  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值