gpt4 book ai didi

python - SSH 连接不持久

转载 作者:太空狗 更新时间:2023-10-29 21:07:07 27 4
gpt4 key购买 nike

我有以下脚本,它通过 SSH 连接到网络服务器并执行一些命令,出于某种原因,SSH 连接打开但在执行命令时它关闭(我认为),结果命令失败并显示以下内容错误?谁能提供如何使 SSH 连接持久的信息?

#!/usr/bin/python
import os
import sys
import json
import fileinput
import pwd
from subprocess import Popen, PIPE, STDOUT
import re
import paramiko
import MySQLdb

resource = r'qca-cdit-01'
ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(resource, username='username', password='passwordname')
#chan = ssh.get_transport().open_session()
chan = ssh.invoke_shell()
chan.get_pty()

commandstringlist = \
['/local/mnt/workspace/LA_host_builds/AU_LINUX_ANDROID_LA.BF64.1.2.1_RB2.05.01.01.081.031_msm8992',
'cd frameworks/base',
'git fetch ssh://cdit@review-android.company.com:29418/platform/frameworks/base refs/changes/21/1260821/2 && git cherry-pick FETCH_HEAD']
for cmd_val in commandstringlist:
#chan.exec_command(cmd_val)
chan.send(cmd_val)
print(chan.recv(1024))

错误:

Traceback (most recent call last):
File "ssh_test.py", line 21, in <module>
chan.get_pty()
File "/usr/local/lib/python2.7/dist-packages/paramiko/channel.py", line 60, in _check
return func(self, *args, **kwds)
File "/usr/local/lib/python2.7/dist-packages/paramiko/channel.py", line 177, in get_pty
self._wait_for_event()
File "/usr/local/lib/python2.7/dist-packages/paramiko/channel.py", line 1086, in _wait_for_event
raise e
paramiko.ssh_exception.SSHException: Channel closed

最佳答案

您使用 exec_command 执行的每个命令都有自己的 channel ,因此也有自己的上下文。该上下文包括工作目录。您在一个上下文中更改工作目录,然后尝试在另一个上下文中使用它。相反,对所有命令使用相同的 channel 。您可以打开一个 channel 并使用它,也可以一次发出所有命令。

commandstringlist = ['cd /local/mnt/workspace/test2 && cd data/log && git fetch ssh://username@review-android.company.com:29418/platform/data/log refs/changes/21/1260821/2 && git cherry-pick FETCH_HEAD']

这里有一些其他问题可以更详细地解释这一点。

https://unix.stackexchange.com/questions/80821/why-does-cd-command-not-work-via-ssh https://superuser.com/questions/46851/keeping-working-directory-across-ssh https://stackoverflow.com/a/6770272/492773

关于python - SSH 连接不持久,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30037401/

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