python人人可以学Python程序员

SSH | Python ssh远程服务器的简单使用

2017-08-31  本文已影响101人  HiWoo
人人可以学Python.jpg

Python ssh模块

python有很多第三方的SSh模块,我们也可以使用python自带的ssh模块,进行一些常用的操作

Code: 1. 文件上传,下载,命令执行

#!/usr/bin/env python
# -*-coding:utf-8-*-
import ssh

__author__ = "Allen Woo"

def connect_host(ip, port, username, password):
    '''
    连接远程主机
    '''
    client = ssh.SSHClient()
    client.set_missing_host_key_policy(ssh.AutoAddPolicy())
    try:
        client.connect(ip, port = port,
                       username = username,
                       password = password)
    except Exception,e:
        print e
        return False
    return client

# 连接远程服务器
client = connect_host(192.168.1.111,  22,  "test",  "123456")
# 文件下载
sftp = client.open_sftp()
remote_file = "/home/work/test.txt"
local_save_path = "/home/work/temp_file/text.txt"

sftp.get(remote_file, local_save_path)

# 文件上传差不多
remote_save_path = "/home/work/upload/test.txt"
local_file = "/home/work/text.txt"
sftp.put(local_file, remote_save_path)

# 命令执行
stdin, stdout, stderr = client.exec_command("ls -l ")
r = stdout.read()
print(r)

Code: 2. 获取远程服务器的目录list

def sftp_walkdir(sftp, path):
    '''
    递归获取path下的所有文件与目录
    :param sftp: python ssh sftp object
    :param path:
    :return:
    '''
    now_dirname = os.path.split(path)[-1]
    backups = []
    files = sftp.listdir_attr(path)
    for f in files:
        tpath = "{}/{}".format(path, f.filename)
        if f.longname[0] == "d":

            r = sftp_walkdir(sftp, tpath)
            backups.append(r)
        else:
            backups.append({"filename":f.filename, "_path_":tpath})

    return {now_dirname:backups, "_path_":path}

# 测试下
# 连接远程服务器
client = connect_host(192.168.1.111,  22,  "test",  "123456")
r = sftp_walkdir(sftp, "/home/work/sshtest")
print(json.dumps(r, sort_keys=True, indent=2))

看下Code2 目录list的结果

{
  "_path_": "/home/work/sshtest", 
  "sshtest": [
    {
      "_path_": "/home/work/sshtest/test2.txt", 
      "filename": "test2.txt"
    }, 
    {
      "_path_": "/home/work/sshtest/test1.txt", 
      "filename": "test1.txt"
    }, 
    {
      "_path_": "/home/work/sshtest/sshtest_222", 
      "sshtest_222": [
        {
          "_path_": "/home/work/sshtest/sshtest_222/test_lalalal.txt", 
          "filename": "test_lalalal.txt"
        }, 
        {
          "_path_": "/home/work/sshtest/sshtest_222/sshtest_333_222", 
          "sshtest_333_222": [
            {
              "_path_": "/home/work/sshtest/sshtest_222/sshtest_333_222/test_ooooo.txt", 
              "filename": "test_ooooo.txt"
            }
          ]
        }, 
        {
          "_path_": "/home/work/sshtest/sshtest_222/sshtest_333", 
          "sshtest_333": []
        }, 
        {
          "_path_": "/home/work/sshtest/sshtest_222/test_hahahah.txt", 
          "filename": "test_hahahah.txt"
        }
      ]
    }
  ]
}

还有其他功能,可以直接看文档或者查看源码, 就先这样吧

上一篇下一篇

猜你喜欢

热点阅读