编程语言
首页 > 编程语言> > python通过ssh读写远程数据

python通过ssh读写远程数据

作者:互联网

1.适用场景

  需要读取(写)多台远程机器下的一个或多个文件,如果要通过 os.system('scp ......')来完成就必须配置免密登陆,比较麻烦

2.准备工作,

  安装依赖

  pip install ssh2,

  如未安装pip可以通过网页下载ssh2.zip文件然后通过动态加载

import os
import imp

os.system('unzip ssh2.zip')
imp.load_package('ssh2','./ssh2')

3.具体操作方式,

  

import socket

from odps import ODPS
from ssh2.session import Session
from datetime import date, timedelta, datetime
from ssh2.sftp import LIBSSH2_FXF_READ, LIBSSH2_SFTP_S_IRUSR

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, 22))

session = Session()
session.handshake(sock)
session.userauth_password(user, pwd)

sftp = session.sftp_init()
channel = session.open_session()

channel.execute("cat demo'")
channel.wait_eof()
channel.close()
channel.wait_closed()

size, data = channel.read()
files_str = unicode(data, 'utf-8')
while size > 0:
        size, data = channel.read()
        files_str = files_str + unicode(data, 'utf-8')

print files_str

 

标签:socket,python,读写,session,ssh2,ssh,str,import,channel
来源: https://www.cnblogs.com/yangyang12138/p/11351231.html