我正在尝试使用paramiko
实现一个(本地假的)服务器,它响应自定义命令,就像原始命令一样,用于测试目的。主要是从提供的demo server进行复制,我设法提出了这种自定义方法来处理通过paramiko.ServerInterface
实现的服务器的exec_requests:
def check_channel_exec_request(self,channel,command):
print("User wants to execute '%s'" %(command))
comm_main, comm_add = command.decode().split(sep=" ",maxsplit=1)
if comm_main in self.allowed_commands:
chout = channel.makefile("w")
subprocess.Popen(command,stdout=chout)
return True
else:
return False
服务器运行后:
PORT = 50007 # The same port as used by the server
HOST = 'localhost'
host_key = paramiko.RSAKey(filename = <FILEPATH>)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((HOST,PORT))
sock.listen(1)
conn, addr = sock.accept() # Connected!
with conn:
trans = paramiko.Transport(conn)
trans.add_server_key(host_key)
trans.set_subsystem_handler("job",JobHandler)
server = FakeCluster() # Custom class sublassing paramiko.ServerInterface
trans.start_server(server=server)
chan = trans.accept() # Accept authentication from client
while trans.is_active(): # Do not close until inactive
time.sleep(1)
chan.close()
客户端将尝试以下列方式执行echo 123
:
PORT = 50007 # The same port as used by the server
HOST = 'localhost'
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.bind((HOST,PORT))
ssh = paramiko.client.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(HOST, PORT,username=<USERNAME>,password=<PASSWORD>)
ssh.exec_command("echo 123")
现在,我收到错误,试图执行subprocess
'ChannelFile' has no attribute 'fileno'
。此外,我想知道如何稍后执行python脚本作为exec_command
调用的自定义命令。 (也许通过调用调用python脚本的批处理文件?)
答案 0 :(得分:0)
你的问题真的很混乱,这就是我与远程服务器通信所做的。
本地机器:窗口
远程计算机:ubuntu
远程机器上的命令:'who'
import paramiko
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('192.268.21.26',port=22,username='root',password='default')
stdin,stdout,stderr=ssh.exec_command('who')
output=stdout.readlines()
print '\n'.join(output)
#output
#root tty7 2017-11-28 14:13 (:0)
#if you wish to execute a python file there , this should work
stdin,stdout,stderr=ssh.exec_command('python file.py')