在python中使用paramiko(或不使用)远程读取文件

问题描述 投票:0回答:1

我想在远程计算机上读取文件。我可以使用paramiko

文件通过换行符不断更新。我试图实现一个Python脚本来读取它。这里是代码中有趣的部分:

import glob
import sys
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import os
import pandas as pd
from scipy.linalg import norm
import time
import paramiko
import select

if __name__ == "__main__": 
    print("...starting")

    # a lot of stuff here in the middle

    ssh_client = paramiko.SSHClient()
    ssh_client.load_system_host_keys()
    ssh_client.connect(hostname='xxx.xx.xx.xxx',username='user',password='pass')

    print("...starting transport:")
    transport = ssh_client.get_transport()
    channel = transport.open_session()
    channel.exec_command("cat /tmp/ciao.txt")
    while True:
        rl, wl, xl = select.select([channel],[],[],0.0)
        #print(rl.readlines())
        if len(rl) > 0:
            #print("printing")
            string_in_file = channel.recv(1024)
            if len(string_in_file) > 0:
                #print("printing")
                print(string_in_file)

问题:在开头和之后均正确读取了文件,每条新写的行均被完全忽略,或者至少对建议的脚本输出没有任何影响。关于编写时如何阅读换行的任何建议?

关于如何获得相同结果(即使没有paramiko的任何其他想法也非常受欢迎。唯一的限制是使用python。

python ssh remote-access paramiko
1个回答
0
投票

[tail -f将继续关注文件,为您提供更多输出。

import glob
import sys
import os
import time
import paramiko
import select

if __name__ == "__main__": 
    print("...starting")

    # a lot of stuff here in the middle

    ssh_client = paramiko.SSHClient()
    ssh_client.load_system_host_keys()

    # for test get "user,pw" in ./test.pw
    user, pw = open('test.pw').readline().strip().split(",")
    ssh_client.connect(hostname='localhost',username=user,password=pw)

    print("...starting transport:")
    transport = ssh_client.get_transport()
    channel = transport.open_session()
    # 1GB is include first Gig - just a way to get all of the 
    # file instead of the last few lines
    # include --follow=name instead of -f if you want to keep
    # following files that are log rotated
    channel.exec_command("tail -f --lines=1GB /tmp/test.txt")
    while True:
        # (don't melt cpu's with a zero timeout)
        rl, wl, xl = select.select([channel],[],[])
        #rl, wl, xl = select.select([channel],[],[],0.0)
        if rl:
            string_in_file = channel.recv(1024)
            if len(string_in_file) > 0:
                print(string_in_file)
            else:
                print("channel disconnected")
                break
© www.soinside.com 2019 - 2024. All rights reserved.