2014-04-03 30 views
1

我需要在python中执行带参数的ssh命令。我已经能够执行ssh命令。但是,我无法弄清楚,如何传递参数。在python中执行参数的ssh命令

的命令: SSH -L 22222:本地主机:5434 [email protected]

下面是代码:

ssh = paramiko.SSHClient(); 
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()); 
ssh.connect("155.97.73.252", username="sayan", password="#####"); 
+0

这只是一个命令做ssh端口转发,这引发了问题,为什么不使用ssh? [端口转发与paramiko](http://stackoverflow.com/a/12106387/642070)使用[paramiko演示](https://code.ros.org/trac/wg-ros-pkg/browser/pkg/ trunk/paramiko/demos?rev = 30)forward.py,如果你想坚持使用python。 – tdelaney

回答

2

的paramiko例

class RunCommand(cmd.Cmd): 
     """ Simple shell to run a command on the host """ 



    prompt = 'ssh > ' 

    def __init__(self): 
     cmd.Cmd.__init__(self) 
     self.hosts = [] 
     self.connections = [] 

    def do_add_host(self, args): 
     """add_host 
     Add the host to the host list""" 
     if args: 
      self.hosts.append(args.split(',')) 
     else: 
      print "usage: host " 

    def do_connect(self, args): 
     """Connect to all hosts in the hosts list""" 
     for host in self.hosts: 
      client = paramiko.SSHClient() 
      client.set_missing_host_key_policy(
       paramiko.AutoAddPolicy()) 
      client.connect(host[0], 
       username=host[1], 
       password=host[2]) 
      self.connections.append(client) 

    def do_run(self, command): 
     """run 
     Execute this command on all hosts in the list""" 
     if command: 
      for host, conn in zip(self.hosts, self.connections): 
       stdin, stdout, stderr = conn.exec_command(command) 
       stdin.close() 
       for line in stdout.read().splitlines(): 
        print 'host: %s: %s' % (host[0], line) 
     else: 
      print "usage: run " 

    def do_close(self, args): 
     for conn in self.connections: 
      conn.close() 

if __name__ == '__main__': 
    RunCommand().cmdloop() 
Example output: 

ssh > add_host 127.0.0.1,jesse,lol 
ssh > connect 
ssh > run uptime 
host: 127.0.0.1: 14:49 up 11 days, 4:27, 8 users, 
load averages: 0.36 0.25 0.19 
ssh > close 

织物示例

from fabric import tasks 

env.hosts = ['localhost', 'sunflower.heliotropic.us'] 
pattern = re.compile(r'up (\d+) days') 

# No need to decorate this function with @task 
def uptime(): 
    res = run('uptime') 
    match = pattern.search(res) 
    if match: 
     days = int(match.group(1)) 
     env['uts'].append(days) 

def main(): 
    env['uts'] = [] 
    tasks.execute(uptime) 
    uts_list = env['uts'] 
    if not uts_list: 
     return # Perhaps we should print a notice here? 
    avg = sum(uts_list)/float(len(uts_list)) 
    print '-' * 80 
    print 'Average uptime: %s days' % avg 
    print '-' * 80 

if __name__ == '__main__': 
    main() 
+0

但是,如何传递参数-L 22222:localhost:5434 ??? – user2284140

+0

如何开展工作, 它提供了Python中的SSH接口, 一旦你连接到你可以为你在正常的SSH终端 运行只是通过与param命令运行命令(有或没有PARAMS)服务器来运行方法它会运行 – onsy