python subprocess popen输入密码_使用subprocess.Popen通过SSH或SCP发送密码

下面是一个使用pexpect密码的ssh函数:def ssh(host, cmd, user, password, timeout=30, bg_run=False):

"""SSH'es to a host using the supplied credentials and executes a command.

Throws an exception if the command doesn't return 0.

bgrun: run command in the background"""

fname = tempfile.mktemp()

fout = open(fname, 'w')

options = '-q -oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null -oPubkeyAuthentication=no'

if bg_run:

options += ' -f'

ssh_cmd = 'ssh %s@%s %s "%s"' % (user, host, options, cmd)

child = pexpect.spawn(ssh_cmd, timeout=timeout)

child.expect(['password: '])

child.sendline(password)

child.logfile = fout

child.expect(pexpect.EOF)

child.close()

fout.close()

fin = open(fname, 'r')

stdout = fin.read()

fin.close()

if 0 != child.exitstatus:

raise Exception(stdout)

return stdout

使用scp应该可以实现类似的功能。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值