[英]scp to a remote server using pexpect
我正在嘗試學習一些關於pexpect的內容:特別是我正在嘗試將文件從筆記本電腦復制到遠程服務器。 我遇到了一個奇怪的行為:如果我逐行編寫它,或多或少相同的代碼可以工作,但如果我將它作為腳本運行則不會。 這是我逐行編寫的內容:
child = pexpect.spawn('scp pathdir/file.ext username@hostname:pathdir')
r=child.expect ('assword:')
r
它返回0,我用密碼完成了工作
child.sendline ('password')
當我ssh到服務器時,我在那里找到了我的文件。 所以我收集了腳本中的所有步驟; 它退出沒有錯誤,但文件沒有被復制...為什么? 但更重要的是,我該如何解決這個問題呢?
這是腳本:
child = pexpect.spawn('scp pathdir/file.ext username@hostname:pathdir')
r=child.expect ('assword:')
print r
if r==0:
child.sendline ('password')
child.close()
我不確定pexpect是如何工作的所以我打印r確保它是0.它確實是。
我最近遇到了“同樣”的問題。 這就是我做到的。 我希望這肯定會對你有所幫助。
你的問題: I'm not sure how pexpect works so I print r to be sure it is 0. And it is.
是的,它是零。
請嘗試以下代碼:
try:
var_password = "<YOUR PASSWORD>" Give your password here
var_command = "scp pathdir/file.ext username@hostname:pathdir"
#make sure in the above command that username and hostname are according to your server
var_child = pexpect.spawn(var_command)
i = var_child.expect(["password:", pexpect.EOF])
if i==0: # send password
var_child.sendline(var_password)
var_child.expect(pexpect.EOF)
elif i==1:
print "Got the key or connection timeout"
pass
except Exception as e:
print "Oops Something went wrong buddy"
print e
child.expect可以接受多個參數。 在這種情況下,您必須以列表的形式發送這些參數。 在上面的場景中,如果pexpect.spawn的輸出是“password:”,那么i
將得到0作為輸出,如果遇到EOF
而不是“password”,則i
的值將為1。
我希望這會清除你的懷疑。 如果沒有,請告訴我。 我會盡力為你加強解釋。
發送密碼即
child.sendline('password')
寫:
child.expect(pexpect.EOF)
這等待文件復制完成
我遇到了同樣的問題。 當我指定客戶端的主目錄(〜/)作為目標時,就發生了這種情況。 這在手動輸入scp命令時工作正常,但出於某種原因,在使用pexpect時卻沒有。 簡單地使用相對或絕對目標目錄路徑解決了我的問題。
您必須使用child.interact()
完成代碼,然后它將運行您之前編寫的所有命令。
它看起來像這樣:
child = pexpect.spawn('scp pathdir/file.ext username@hostname:pathdir')
r=child.expect ('assword:')
print r
if r==0:
child.sendline ('password')
child.interact()
child.close()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.