[英]what's the best way to get file/directory information that's supported on Unix/Linux remote host
我有一個python代碼,需要在Unix / Linux(操作系統名稱:HP-UX / RedHat / SunOS / AIX / Linux /等)的遠程主機上獲取文件或目錄信息。
程序SSH進入遠程主機(使用paramiko庫)並執行ls -l
或ls -ld
具體取決於它是文件還是目錄。
我需要的信息是:
然而, ls
的問題是:
我正在尋找一個python庫或簡單的可移植可執行文件(如果有的話)。
我考慮過的解決方案(但似乎不可行)
有什么建議么?
stat
做的伎倆嗎? 它似乎具有您正在尋找的所有功能,應該已經安裝好了。
http://ss64.com/bash/stat.html
如果你想在python中工作,python有一個名為stat
的內置庫,它提供了類似的功能:
SFTP是SSH-2中內置的標准文件傳輸協議。 因此,如果您可以通過SSH連接到遠程主機,那么很可能您可以以標准方式使用SFTP來列出和統計文件。 SFTP 得到了包括OpenSSH在內的SSH服務器的廣泛支持 。
paramiko可能是Python最流行的SSH / SFTP包裝器。 以下是使用paramiko執行SFTP統計的示例腳本:
import paramiko
ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.WarningPolicy()) # Only warn on no known_hosts
ssh.connect("localhost", username="sam")
sftp = ssh.open_sftp()
try:
listing = sftp.listdir_attr(".")
print(listing[0:10])
my_stat = sftp.stat(".")
print(my_stat)
print(my_stat.st_size, my_stat.st_mtime, my_stat.st_atime, my_stat.st_uid, my_stat.st_gid)
except IOError:
pass
ssh.close()
當然這只是一個簡單的例子,你可以用paramiko SFTP API做更多的事情 - 文檔 。
更新:相關文章: Python中的SFTP? (獨立於平台)
你可能也沒有在所有這些機器上安裝python,但我敢打賭你甚至在HPUX盒子上都有一些古老的硬殼版perl。
~/tmp/t3 $perl -e 'print (join (",", (stat("t.awk"))), "\n");'
655368,160089,33204,1,16257,200,0,178,1480727842,1480710575,1480710575,4096,8
~/tmp/t3 $stat t.awk
File: `t.awk'
Size: 178 Blocks: 8 IO Block: 4096 regular file
Device: a0008h/655368d Inode: 160089 Links: 1
Access: (0664/-rw-rw-r--) Uid: (16257/mcgowan) Gid: ( 200/ users)
Access: 2016-12-02 17:17:22.000000000 -0800
Modify: 2016-12-02 12:29:35.000000000 -0800
Change: 2016-12-02 12:29:35.000000000 -0800
這是perl stat字段的交叉引用:
0 dev device number of filesystem
1 ino inode number
2 mode file mode (type and permissions)
3 nlink number of (hard) links to the file
4 uid numeric user ID of file's owner
5 gid numeric group ID of file's owner
6 rdev the device identifier (special files only)
7 size total size of file, in bytes
8 atime last access time in seconds since the epoch
9 mtime last modify time in seconds since the epoch
10 ctime inode change time in seconds since the epoch (*)
11 blksize preferred I/O size in bytes for interacting with the
file (may vary from file to file)
12 blocks actual number of system-specific blocks allocated
on disk (often, but not always, 512 bytes each)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.