我正在使用 Python 2.7.6 和 Paramiko 模块(在 Linux 服务器上)连接到 Windows 服务器并发送一些命令并获取输出。我有一个连接功能,它获取远程 Windows 服务器的 IP、用户名和密码,当发生这种情况时我得到一个 sshobj。我的问题是如何使用它发送远程调用?
如果是本地系统,我只会说“os.system”,但不确定远程调用。有人可以帮忙吗?
我的代码如下所示: sys.path.append("/home/me/code")
import libs.ssh_connect as ssh
ssh_obj = ssh.new_conn(IP, username, password)
stdin, stdout, stderr = ssh_obj.exec_command("dir") #since the remote system I am SSHing into is Windows.
我的“new_conn”看起来像这样:
import paramiko
def new_conn(IP, username, password):
ssh_obj = paramiko.SSHClient()
ssh_conn.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_conn.connect(IP, username, password), timeout=30)
return ssh_obj
我从 stdin、stdout 和 stderror 得到的所有信息都是“事件的;1 个开放 channel 和一些信息,如 ChannelFile、aes 等......”。
我希望在我的 Linux 上看到 Windows 的“dir”输出..
尝试了“stdout.read()”和“stdout.readlines()”,但前者输出的是“stdout”,后者输出的是“[]”!
谢谢!
最佳答案
我在 Windows 上安装了 FreeSSHd,它可以正常工作!
FreeSSHd教程:(中文) https://jingyan.baidu.com/article/f7ff0bfc1ebd322e27bb1344.html
代码:(Python 3)
import paramiko
hostname = "windows-hostname"
username = "windows-username"
password = "windows-password"
cmd = 'ifconfig'
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname,username=username,password=password)
print("Connected to %s" % hostname)
except paramiko.AuthenticationException:
print("Failed to connect to %s due to wrong username/password" %hostname)
exit(1)
except Exception as e:
print(e.message)
exit(2)
try:
stdin, stdout, stderr = ssh.exec_command(cmd)
except Exception as e:
print(e.message)
err = ''.join(stderr.readlines())
out = ''.join(stdout.readlines())
final_output = str(out)+str(err)
print(final_output)
关于python - 如何使用 paramiko ssh 对象向 Windows 和 Linux 服务器发送远程调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30552812/