linux popen 密码,使用subprocess.Popen通过SSH或SCP发送密码

本文介绍了一个使用Python pexpect库来简化SSH登录并执行远程命令的过程。通过定义函数ssh,实现了利用提供的凭证SSH到主机并执行指定命令的功能。此外还支持在后台运行命令,并详细解释了实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

sjbx..

10

这是ssh使用密码的函数pexpect:

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、付费专栏及课程。

余额充值