Python pexpec 解决scp ssh


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

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

#!/usr/bin/python2.7
import pexpect
import os, sys, getpass


def ssh_command(user, host, password, command):
	ssh_newkey = '.*(yes/no).*'
        passwd_key = '.*assword.*'
	child = pexpect.spawn('ssh -l %s %s %s' %(user, host, command))
	child.logfile = sys.stdout
	i = child.expect([pexpect.TIMEOUT, ssh_newkey, passwd_key])

	if i == 0: #timeout
		print child.before
		print "Error time out"
		print child.after
		return None
	if i ==1 :
		child.sendline('yes')
		i = child.expect([pexpect.TIMEOUT, passwd_key])
		if i == 0:
			print child.before
			print 'time out ERROR'
			print child.after
			return None
	child.sendline(password)
	return child


def scp2(ip, user, passwd, dst_path, filename):
    passwd_key = '.*assword.*'
    if os.path.isdir(filename): 
        cmdline = 'scp -r %s %s@%s:%s' % (filename, user, ip, dst_path) 
    else: 
        cmdline = 'scp %s %s@%s:%s' % (filename, user, ip, dst_path) 
    try:
        child = pexpect.spawn(cmdline)
        child.expect(passwd_key)
        child.sendline(passwd)
        child.expect(pexpect.EOF)
        #child.interact()
        #child.read()
        #child.expect('$')
        print "uploading" 
    except:
        print "upload faild!"

def main():
    host = raw_input('Hostname:')
    user = raw_input('User:')
    password = getpass.getpass()
    command = raw_input('Command:')
    child = ssh_command(user, host, password, command)
    child.expect(pexpect.EOF)
    print child.before

if __name__ == "__main__":
    
main()
 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值