问题描述
我正在尝试使用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特性? 任何见解将不胜感激。
1楼
像往常一样,结果比我想的要简单得多。
string = ""
for arg in command:
string = string + " " + arg
上面的代码产生“传递的任何命令”,结果证明Windows对前面的空间反应极差,而linux不在乎。 新的代码段是:
string = ""
first = True
for arg in command:
if first:
string = string + arg
first = False
else:
string = string + " " + arg
我将标题和详细信息保持不变,以希望帮助任何犯过与我完全相同的错误的人。