通过SSH访问远程主机并在Python中发送命令

问题描述 投票:0回答:2

我需要使用我的id访问远程主机,然后发送

pbrun
命令切换到root。到目前为止我有这个代码:

import time
import paramiko
output_file = 'paramiko.org'

ssh = paramiko.SSHClient()

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('host', port=22, username='test', password='XXXXXXX')
stdin, stdout, stderr = ssh.exec_command('pbrun ohsoap -u root')
time.sleep(0.1

md_output = stdout.read()
print('log printing: ',md_output)

with open(output_file, "w+") as file:
    file.write(str(md_output))
stdin.flush()
print(stdout.readlines())

但是,发送

pbrun
命令后,会要求输入密码。如何向正在运行的程序提供密码?

python paramiko
2个回答
0
投票

我相信这可以帮助您快速启动并了解想法:

import time
import paramiko

output_file = 'paramiko_output.txt'
hostname = 'host'
username = 'test'
password = 'XXXXXXX'
command = 'pbrun ohsoap -u root'

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname, port=22, username=username, password=password)

chan = ssh.invoke_shell()
chan.send(command  + '\n')
time.sleep(1)
chan.send(password + '\n')
time.sleep(1)
md_output = chan.recv(1024).decode('utf-8')
print('log printing:', md_output)

with open(output_file, "w+") as file:
    file.write(md_output)

ssh.close()

如果您能使用钥匙来处理这些事情那就最好了。


0
投票

非常感谢莫森。你拯救了我的一天,因为我做了一些小改变,它对我来说效果很好:

import time
import paramiko

output_file = 'paramiko_output.txt'
hostname = 'host'
username = 'username'
password = 'password'
command = 'pbrun ohsoap -u root'

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname, port=22, username=username, password=password)
chan = ssh.invoke_shell()
time.sleep(3)
chan.send(command + '\n')
time.sleep(3)
chan.send(password + '\n')
time.sleep(3)
chan.send('id' + '\n')
time.sleep(3)
md_output = chan.recv(1024).decode('utf-8')
print('log printing:', md_output)

with open(output_file, "w+") as file:
file.write(md_output)

 ssh.close()
© www.soinside.com 2019 - 2024. All rights reserved.