簡體   English   中英

使用python,SSH檢查遠程服務器中的文件大小

[英]checking file size in a remote server using python, SSH

有人請幫忙!

我目前正在編寫一個python腳本來實際檢索本地PC和遠程服務器中的文件大小。 然后,我要做的是,我比較文件的大小是否相同。 下面是我的代碼:

A = "/path/of/the/file/in/my/local/PC"
B = "/path/of/the/file/in/remote/PC"

statinfo1 = os.stat(A)
statinfo2 = os.system ("ssh" " root@192.168.10.1" " stat -c%s "+B)

if statinfo1 == statinfo2 :
   print 'awesome'
else :
   break

遇到的問題:statinfo1可以返回本地PC中的文件大小,但是statinfo2不能返回文件大小。 我想使用SSH方法

為什么不使用Paramiko SSHClient 它是一個漂亮的第三方庫,簡化了ssh訪問。

因此,要檢查遠程文件的文件大小,代碼將類似於:

import paramiko, base64

B = "/path/of/the/file/in/remote/PC"

key    = paramiko.RSAKey(data=base64.decodestring('AAA...'))
client = paramiko.SSHClient()
client.get_host_keys().add('ssh.example.com', 'ssh-rsa', key)
client.connect('192.168.10.1', username='root', password='yourpassword')
stdin, stdout, stderr = client.exec_command("stat -c " + B)
for line in stdout:
    print '... ' + line.strip('\n')
client.close()

也要檢查此- 如何獲取遠程文件的大小? 使用Paramiko進行SSH編程

使用paramiko或pexpect可以使用,但對於您在此處的簡單用例而言,可能有點繁重。

您可以使用僅依賴於底層操作系統的ssh和python內置subprocess模塊的輕量級解決方案。

import os
A = "/path/of/the/file/in/my/local/PC"
B = "/path/of/the/file/in/remote/PC"

# I assume you have stat visible in PATH on both the local and remote machine,
# and that you have no password nags for ssh because you've setup the key pairs 
# already (using, for example, ssh-copy-id)

statinfo1 = subprocess.check_output('stat -c%s "{}"'.format(A), shell=True)
statinfo2 = subprocess.check_output('ssh root@192.168.10.1 stat -c%s "{}"'.format(B), shell=True)

你也可以看看面料 ,便於遠程任務。

fabfile.py:

1 from fabric.api import run, env
2
3 env.hosts = ['user@host.com']
4
5 def get_size(remote_filename):
6     output = run('stat -c \'%s\' {0}'.format(remote_filename))
7     print 'size={0}'.format(output)

Shell命令:

~ $ fab get_size:"~/.bashrc"
statinfo1 = os.stat(A)
statinfo2 = os.system ("ssh" " root@192.168.10.1" " stat -c%s "+B)

os.stat返回什么?

  • 具有多個字段的數據結構,其中一個是大小。

os.system返回什么?

  • 它返回一個int表示所調用程序的退出代碼。

因此,它們之間的比較注定會失敗。 考慮@Srikar建議的Paramiko,或使用這種方法解決問題。

對於后者,請嘗試以下操作:

import commands

statinfo1 = os.stat(A).st_size
cmd = "ssh" " root@192.168.10.1" " stat -c%s "+B
rc, remote_stat = commands.getstatusoutput(cmd)

if rc != 0:
   raise Exception('remote stat failure: ' + remote_stat)

statinfo2 = int(remote_stat)

if statinfo1 == statinfo2 :
   print 'awesome'
else :
   break

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM