python中的paramiko模块是用来实现ssh连接到远程服务器上的库,在进行连接的时候,可以用来执行命令,也可以用来上传文件。

1、得到一个连接的对象

在进行连接的时候,可以使用如下的代码:

def connect(host):
'this is use the paramiko connect the host,return conn'
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
# ssh.connect(host,username='root',allow_agent=True,look_for_keys=True)
ssh.connect(host,username='root',password='root',allow_agent=True)
return ssh
except:
return None

在connect函数中,参数是一个主机的IP地址或者是主机名称,在执行这个方法之后,如果成功的连接到服务器,那么就会返回一个sshclient对象。

第一步是建立一个SSHClient的对象,然后设置ssh客户端允许连接不在know_host文件中的机器,然后就尝试连接服务器,在连接服务器的时候,可以使用两种方式:一种方式是使用秘钥的方式,也就是参数look_for_keys,这里用设置密码寻找,也可以直接使用密码的方式,也就是直接使用参数password,从而最后返回一个连接的对象。

2、 获取设置的命令

在进行paramiko连接之后,那么必须要得到需要执行的命令,如下代码所示:

def command(args,outpath):
'this is get the command the args to return the command'
cmd = '%s %s' % (outpath,args)
return cmd

在参数中,一个是args,一个outpath,args表示命令的参数,而outpath表示为可执行文件的路径,例如/usr/bin/ls -l。在其中outpath也就是/usr/bin/ls ,而参数为-l

这个方法主要是用来组合命令,将分开的参数作为命令的一部分进行组装。

3、 执行命令

在连接过后,可以进行直接执行命令,那么就有了如下的函数:

def exec_commands(conn,cmd):
'this is use the conn to excute the cmd and return the results of excute the command'
stdin,stdout,stderr = conn.exec_command(cmd)
results=stdout.read()
return results

在此函数中,传入的参数一个为连接的对象conn,一个为需要执行的命令cmd,最后得到执行的结果,也就是stdout.read(),最后返回得到的结果

4、 上传文件

在使用连接对象的时候,也可以直接进行上传相关的文件,如下函数:

def copy_moddule(conn,inpath,outpath):
'this is copy the module to the remote server'
ftp = conn.open_sftp()
ftp.put(inpath,outpath)
ftp.close()
return outpath

此函数的主要参数为,一个是连接对象conn,一个是上传的文件名称,一个上传之后的文件名称,在此必须写入完整的文件名称包括路径。