我正在使用Python
的Paramiko
在删除服务器中执行命令。代码很简单。
这是我对SSHConn
类的定义:
class SSHConn:
def __init__(self, hostname, user, pwd, filename=None):
self.client = paramiko.SSHClient()
self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.client.connect(hostname, username=user, password=pwd,
key_filename=filename)
self.transport = self.client.get_transport()
self.channel = self.transport.open_session()
所以我正在运行以下代码:
local_ssh = ssh.SSHConn(host, user, passwd)
cmds = ('foo', 'bar')
for cmd in cmds:
local_ssh.channel.exec_command(cmd)
self.log.info(local_ssh.channel.recv(1024))
但是,当我执行以下代码时,我得到了:
INFO:paramiko.transport:Connected (version 2.0, client OpenSSH_6.6.1p1)
INFO:paramiko.transport:Authentication (publickey) failed.
INFO:paramiko.transport:Authentication (password) successful!
INFO:paramiko.transport:Secsh channel 1 opened.
INFO:testsets.testcase:
ERROR:testsets.testcase:Channel is not open
Traceback (most recent call last):
File "/root/fds-src/source/test/integration-framework/testsets/testcases/test_100gb_volume.py", line 87, in runTest
local_ssh.channel.exec_command(cmd)
File "/usr/lib/python2.7/dist-packages/paramiko/channel.py", line 209, in exec_command
raise SSHException('Channel is not open')
SSHException: Channel is not open
ERROR:testsets.testcase:Test Case Test100GBVolume failed.
Traceback (most recent call last):
File "/root/fds-src/source/test/integration-framework/testsets/testcases/test_100gb_volume.py", line 87, in runTest
local_ssh.channel.exec_command(cmd)
File "/usr/lib/python2.7/dist-packages/paramiko/channel.py", line 209, in exec_command
raise SSHException('Channel is not open')
SSHException: Channel is not open
如何保持频道开放?
python大神给出的解决方案
channel
文档对此非常清楚。您需要为每个exec_command
打开一个新通道。
exec_command(* args,** kwds)
在服务器上执行命令。如果服务器允许,则该通道将直接连接到正在执行的命令的stdin,stdout和stderr。
该命令执行完毕后,该通道将关闭且无法重复使用。如果要执行其他命令,则必须打开一个新通道。
SSHClient
对象具有为您执行此操作的exec_command
方法。