python paramiko模块
1. SSH密码认证远程执行命令
#!/usr/bin/python # -*- coding: utf-8 -*- import paramiko import sys hostname = '192.168.1.215' port = 22 username = 'root' password = '123456' client = paramiko.SSHClient() # 绑定实例 client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(hostname, port, username, password, timeout=5) stdin, stdout, stderr = client.exec_command('df -h') # 执行bash命令 result = stdout.read() error = stderr.read() # 判断stderr输出是否为空,为空则打印执行结果,不为空打印报错信息 if not error: print result else: print error client.close()
2. 私钥认证远程执行命令
#!/usr/bin/python # -*- coding: utf-8 -*- import paramiko import sys hostname = '192.168.1.215' port = 22 username = 'root' key_file = '/root/.ssh/id_rsa' cmd = " ".join(sys.argv[1:]) def ssh_conn(command): client = paramiko.SSHClient() key = paramiko.RSAKey.from_private_key_file(key_file) client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(hostname, port, username, pkey=key) stdin, stdout, stderr = client.exec_command(command) # 标准输入,标准输出,错误输出 result = stdout.read() error = stderr.read() if not error: print result else: print error client.close() if __name__ == "__main__": ssh_conn(cmd)
3. 上传文件到远程服务器
#!/usr/bin/python # -*- coding: utf-8 -*- import os, sys import paramiko hostname = '192.168.1.215' port = 22 username = 'root' password = '123456' local_path = '/root/test.txt' remote_path = '/opt/test.txt' if not os.path.isfile(local_path): print local_path + " file not exist!" sys.exit(1) try: s = paramiko.Transport((hostname, port)) s.connect(username=username, password=password) except Exception as e: print e sys.exit(1) sftp = paramiko.SFTPClient.from_transport(s) # 使用put()方法把本地文件上传到远程服务器 sftp.put(local_path, remote_path) # 简单测试是否上传成功 try: # 如果远程主机有这个文件则返回一个对象,否则抛出异常 sftp.file(remote_path) print "上传成功." except IOError: print "上传失败!" finally: s.close()
4. 从远程服务器下载文件
#!/usr/bin/python # -*- coding: utf-8 -*- import os, sys import paramiko hostname = '192.168.1.215' port = 22 username = 'root' password = '123456' local_path = '/root/test.txt' remote_path = '/opt/test.txt' try: s = paramiko.Transport((hostname, port)) s.connect(username=username, password=password) sftp = paramiko.SFTPClient.from_transport(s) except Exception as e: print e sys.exit(1) try: # 判断远程服务器是否有这个文件 sftp.file(remote_path) # 使用get()方法从远程服务器拉去文件 sftp.get(remote_path, local_path) except IOError as e: print remote_path + "remote file not exist!" sys.exit(1) finally: s.close() # 测试是否下载成功 if os.path.isfile(local_path): print "下载成功." else: print "下载失败!"
5. 上传目录到远程服务器
paramiko模块并没有实现直接上传目录的类,已经知道了如何上传文件,再写一个上传目录的代码就简单了,利用os库的os.walk()方法遍历目录,再一个个上传
#!/usr/bin/python # -*- coding: utf-8 -*- import os, sys import paramiko hostname = '192.168.1.215' port = 22 username = 'root' password = '123456' local_path = '/root/abc' remote_path = '/opt/abc' # 去除路径后面正斜杠 if local_path[-1] == '/': local_path = local_path[0:-1] if remote_path[-1] == '/': remote_path = remote_path[0:-1] file_list = [] if os.path.isdir(local_path): for root, dirs, files in os.walk(local_path): for file in files: # 获取文件绝对路径 file_path = os.path.join(root, file) file_list.append(file_path) else: print local_path + "Directory not exist!" sys.exit(1) try: s = paramiko.Transport((hostname, port)) s.connect(username=username, password=password) sftp = paramiko.SFTPClient.from_transport(s) except Exception as e: print e for local_file in file_list: # 替换目标目录 remote_file = local_file.replace(local_path, remote_path) remote_dir = os.path.dirname(remote_file) # 如果远程服务器没目标目录则创建 try: sftp.stat(remote_dir) except IOError: sftp.mkdir(remote_dir) print "%s -> %s" % (local_file, remote_file) sftp.put(local_file, remote_file) s.close()
sftp是安全文件传输协议,提供一种安全的加密方法,sftp是SSH的一部分,SFTPClient类实现了sftp客户端,通过已建立的SSH通道传输文件,与其他的操作,如下:
方法 描述 sftp.getcwd() 返回当前工作目录 sftp.chdir(path) 改变工作目录 sftp.chmod(path, mode) 修改权限 sftp.chown(path, uid, gid) 设置属主属组 sftp.close() 关闭sftp sftp.file(filename, mode=’r’, bufsize=-1) 读取文件 sftp.from_transport(s) 创建SFTP客户端通道 sftp.listdir(path=’.’) 列出目录,返回一个列表 sftp.listdir_attr(path=’.’) 列出目录,返回一个SFTPAttributes列表 sftp.mkdir(path, mode=511) 创建目录 sftp.normalize(path) 返回规范化path sftp.open(filename, mode=’r’, bufsize=-1) 在远程服务器打开文件 sftp.put(localpath, remotepath, callback=None) localpath文件上传到远程服务器remotepath sftp.get(remotepath, localpath, callback=None) 从远程服务器remotepath拉文件到本地localpath sftp.readlink(path) 返回一个符号链接目标 sftp.remove(path) 删除文件 sftp.rename(oldpath, newpath) 重命名文件或目录 sftp.rmdir(path) 删除目录 sftp.stat(path) 返回远程服务器文件信息(返回一个对象的属性) sftp.truncate(path, size) 截取文件大小 sftp.symlink(source, dest) 创建一个软链接(快捷方式) sftp.unlink(path) 删除软链接