gpt4 book ai didi

python - 使用 subprocess.Popen 通过 SSH 或 SCP 发送密码

转载 作者:IT王子 更新时间:2023-10-29 00:08:42 24 4
gpt4 key购买 nike

我正在尝试运行 scp (安全复制)命令使用 subprocess.Popen。登录需要我发送密码:

from subprocess import Popen, PIPE

proc = Popen(['scp', "user@10.0.1.12:/foo/bar/somefile.txt", "."], stdin = PIPE)
proc.stdin.write(b'mypassword')
proc.stdin.flush()

这会立即返回一个错误:

user@10.0.1.12's password:
Permission denied, please try again.

确定密码是正确的。我通过在 shell 上手动调用 scp 轻松验证它。那为什么这行不通呢?

请注意,有许多与此类似的问题,询问关于 subprocess.Popen 并发送自动 SSH 或 FTP 登录的密码:

How can I set a users password in linux from a python script?
Use subprocess to send a password

这些问题的答案不起作用和/或不适用,因为我使用的是 Python 3。

最佳答案

这是一个使用 pexpect 和密码进行 ssh 的函数:

import pexpect
import tempfile

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) #spawnu for Python 3
child.expect(['[pP]assword: '])
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 应该可以实现类似的东西。

关于python - 使用 subprocess.Popen 通过 SSH 或 SCP 发送密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15166973/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com