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