【问题标题】:Execute ssh on windows via python通过python在windows上执行ssh
【发布时间】:2021-04-15 12:30:58
【问题描述】:

我正在尝试执行 ssh 命令: ssh -t user1@hostname "sudo su - user2 -s /bin/bash"

我下面的代码不起作用:

expectations = [('password', '******')]
cmd = ['ssh','-t','user1@hostname','"','sudo','su','-','user2','-s','/bin/bash', '"']
try:
    clean_non_empty_lines = []

    expectations = [(None, None)] + expectations

    p = subprocess.Popen(cmd,stdin=subprocess.PIPE,stderr=subprocess.STDOUT,
        stdout=subprocess.PIPE,
        bufsize=1)

    last_line = None

    for expectation, response in expectations:

        if expectation is not None:
            expectation = re.compile('$(.*)' + expectation + '(.*)')

        if expectation is not None and expectation.search(last_line):
            stdout, stderr = p.communicate(input=bytes(response, 'utf-8'))
        else:
            stdout, stderr = p.communicate()

        if stderr is not None:
            error = str(stderr.decode('ascii')).rstrip()
            print(error)

        if stdout is not None:
            last_line = stdout.decode('utf8')

            for line in iter(re.split('\r\n|\n', last_line)):
                line = str(line.rstrip())

                if line != '':
                    print(line)

                    line = line.strip()

                    if line:
                        clean_non_empty_lines += [line]

    p.stdout.close()
    p.wait()

我收到以下错误:

Pseudo-terminal will not be allocated because stdin is not a terminal.
sudo: no tty present and no askpass program specified

有没有办法让它工作?这样在执行 sudo su - user2.... 之后程序会使用变量 'expectations' 中指定的密码来响应密码提示?

【问题讨论】:

    标签: python python-3.x ssh subprocess


    【解决方案1】:

    试试这个https://pypi.org/project/pysftp/ 我之前用过这个来制作我自己的类似 termius 的应用程序,但最终将电子与节点子进程和 mongo 一起使用。

    ps 我后来刮掉了 while 项目,因为我不知道如何在电子中获取终端窗口。

    【讨论】:

    • 这是为了做 sftp,而不是 OP 试图做的事情。
    【解决方案2】:

    由于su 命令,这可能与您无关,但我可能会让您更近一步:

    我的桌面是 Windows,我必须经常登录到我的 ISP 的共享 Linux 服务器。为此,我使用putty 作为我的客户。为避免在登录时提供密码,我使用PuTTYgen 生成公钥/私钥对。前者我通过其 cPanel 设施安装在我的服务器上,后者进入C:\Users\my-windows-id\.ssh\id_rsa。我现在可以通过SSH Linux 命令执行:

    from subprocess import Popen, PIPE
    
    WINDOWS = False
    
    private_key_file = r'C:\Users\my-windows-id\.ssh\id_rsa' if WINDOWS else '/c/Users/my-windows-id/.ssh/id_rsa'
    p = Popen(f'ssh -i "{private_key_file}" my-domain.com', shell=True, stdout=PIPE, stderr=PIPE, stdin=PIPE)
    stdout, stderr = p.communicate(b'cat malware.txt\nlogout\n')
    print('stdout:\n')
    print(stdout.decode())
    print('stderr:\n')
    print(stderr.decode())
    p.wait()
    

    但是,当我尝试从 Windows 命令提示符运行它时(上面的 WINDOWS 变量设置为 TRUE),出现了问题。弹出以下消息:

    The authenticity of host 'my-domain.com (xx.xx.xx.xx)' can't be established.
    RSA key fingerprint is 0b:a6:08:39:d9:a1:90:2f:bd:a2:ff:2e:67:2d:1a:1f.
    Are you sure you want to continue connecting (yes/no)? yes
    

    我指定yes 看看会发生什么,即使我一开始就不应该收到该消息。该程序确实运行了,但在stderr 输出中的输出是:

    Could not create directory '/home/my-windows-id/.ssh'.
    Failed to add the host to the list of known hosts (/home/my-windows-id/.ssh/known_hosts).
    

    现在我不确定为什么会出现这个错误。我碰巧有一个C:\home 目录,它是一个连接目录,也许这就是问题的原因。但这是寻找known_hosts 文件的错误目录,该文件应该已经有必要的条目。我碰巧在 Windows 下安装了 Git,因此我可以在 Git Bash shell 下运行程序:

    $ python test.py
    stdout:
    
    
    ----------- SCAN SUMMARY -----------
    Known viruses: 2086420
    Engine version: devel-clamav-0.99-beta1-632-g8a582c7
    Scanned directories: 9499
    Scanned files: 91169
    Infected files: 0
    Data scanned: 2075.55 MB
    Data read: 11297.00 MB (ratio 0.18:1)
    Time: 772.194 sec (12 m 52 s)
    
    
    ----------- SCAN SUMMARY -----------
    Known viruses: 2086420
    Engine version: devel-clamav-0.99-beta1-632-g8a582c7
    Scanned directories: 0
    Scanned files: 0
    Infected files: 0
    Data scanned: 0.00 MB
    Data read: 0.00 MB (ratio 0.00:1)
    Time: 4.328 sec (0 m 4 s)
    
    
    ----------- SCAN SUMMARY -----------
    Known viruses: 2086420
    Engine version: devel-clamav-0.99-beta1-632-g8a582c7
    Scanned directories: 0
    Scanned files: 20
    Infected files: 0
    Data scanned: 0.94 MB
    Data read: 0.56 MB (ratio 1.67:1)
    Time: 4.587 sec (0 m 4 s)
    
    
    stderr:
    
    Pseudo-terminal will not be allocated because stdin is not a terminal.
    TERM environment variable not set.
    

    stderr 输出有几条消息,其中一条与stdin 有关,但cat 命令确实有效。

    如果导致问题,这将使您通过初始登录。也许您可以为第二次登录安装第二个公钥/私钥对。我只是不确定一旦建立了 SSH 连接,这是否会对 su 命令产生影响。

    【讨论】:

      猜你喜欢
      • 2016-09-17
      • 2011-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-08
      • 1970-01-01
      • 2011-09-19
      相关资源
      最近更新 更多