zoukankan      html  css  js  c++  java
  • Python pexpec 解决scp ssh

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

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

    [python] view plaincopy在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()  
  • 相关阅读:
    USACO2008 Cow Cars /// oj23323
    USACO2008 Roads Around The Farm /// queue oj23321
    USACO2007 捕牛记 /// queue+桶 oj1503
    哈理工多校算法赛一
    USACO2012 Haybale stacking /// 区间表示法 oj21556
    USACO2012 Broken necklace /// DP oj10103
    USACO2004 cube stacking /// 带权并查集 oj1302
    ACM-ICPC 2018 南京赛区网络预赛 J sum (找一个数拆成两个无平方因子的组合数)
    分层图 (可以选择K条路的权为0,求最短路)
    POJ 3537 Crosses and Crosses(sg博弈)
  • 原文地址:https://www.cnblogs.com/hushaojun/p/4903289.html
Copyright © 2011-2022 走看看