Python pexpec 解决scp ssh


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


def ssh_command(user, host, password, command):
	ssh_newkey = 'Are you sure you want to continue connecting'
	child = pexpect.spawn('ssh -l %s %s %s' %(user, host, command))
	i = child.expect([pexpect.TIMEOUT, ssh_newkey, 'password: '])

	if i == 0: #timeout
		print child.before
		print "Error time out"
		print child.after
		return None
	if i ==1 :
		child.sendline('yes')
		child.expect('password: ')
		i = child.expect([pexpect.TIMEOUT, 'password: '])
		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):
    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('password:')
	child.sendline(passwd)
	child.expect(pexpect.EOF)
	#child.interact()
	#child.read()
	#child.expect('$')
	print "uploading"
    except:
	print "upload faild!"


def main1():
	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

def main():
	pass

if __name__ == "__main__":
	pass

		


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值