【发布时间】:2019-02-19 13:04:31
【问题描述】:
我正在尝试使用 paramiko 通过 ssh 将 powershell 命令发送到带有 OpenSSH 的 Windows 机器。这些命令似乎是成功的(返回代码 0),即使它们应该失败,而且我在管道上没有得到任何输出。当我尝试创建目录之类的命令时,它并没有被创建,这使得命令看起来好像没有到达远程系统,但也没有引发错误。
首先,这是我的代码:
version = self.oscall.run_remote(['java', '-version'])
def run_remote(self, command): # Command is a list of command + args
string = ""
self.timeout = 300
for arg in command:
string = string + " " + arg
self.client.connect(self.host, username=self.user, password=self.pw, timeout=self.timeout)
self.transport = self.client.get_transport()
self.transport.set_keepalive(1)
self.channel = self.transport.open_session(timeout=self.timeout) # transport is abstract connection, session is socket
if self.channel.gettimeout() == None: self.channel.settimeout(self.timeout)
self.channel.exec_command(string)
self.out = self.channel.makefile()
self.err = self.channel.makefile_stderr()
self.output = CallOutput(self.out, self.err, None)
self.output.returncode = self.channel.recv_exit_status()
self.channel.close()
return self.output
class CallOutput(object):
def __init__(self, out, err, rc):
self.out = out.readlines()
self.err = err.readlines()
self.outfile = tempfile.TemporaryFile()
for line in self.out:
if isinstance(line, unicode): line = line.encode('utf-8')
self.outfile.write(line + '\n')
self.outfile.seek(0)
self.errfile = tempfile.TemporaryFile()
for line in self.err:
if isinstance(line, unicode): line = line.encode('utf-8')
self.errfile.write(line + '\n')
self.errfile.seek(0)
self.returncode = rc
对不起,文字墙,但我是为了完整性。这是一个更大的应用程序的一部分。
这段代码可以完美地连接到 Linux,所以我不认为会有很多小错误。返回码始终为 0,即使对于垃圾也是如此,并且管道上永远不会有任何输出。如果我只使用终端运行命令,我会得到正确的输出:
$ ssh testuser@testwin.internal.com 'java -version'
Warning: Permanently added 'testwin.internal.com,10.10.10.12' (ECDSA) to the
list of known hosts.
testuser@testwin.internal.com's password:
java version "1.8.0_121"
Java(TM) SE Runtime Environment (build 1.8.0_121-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.121-b13, mixed mode)
$ echo $?
0
$ ssh testuser@testwin.internal.com 'foo'
foo : The term 'foo' is not recognized as the name of a cmdlet, function, script file, or
operable program. Check the spelling of the name, or if a path was included, verify that the path
is correct and try again.
At line:1 char:1
+ foo
+ ~~~
+ CategoryInfo : ObjectNotFound: (foo:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
$ echo $?
1
我能想到的 Linux 和 Windows 进程之间的唯一区别是,在 Windows 上我们必须使用密码,因为我们还没有设置无密码 ssh。我错过了什么奇怪的 Windows 特性?任何见解将不胜感激。
【问题讨论】:
标签: python powershell paramiko openssh