我的代碼:SSH到AWS服務器和編輯hosts文件
出於某種原因,這似乎無限循環和重複打印「here2」和「LS -lah」輸出。有什麼不明顯的事情我做錯了嗎?
def update_hosts_file(public_dns,hosts_file_info):
for dns in public_dns:
print 'here2'
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # wont require saying 'yes' to new fingerprint
key_path = os.path.join(os.path.expanduser(KEY_DIR), KEY_NAME)+'.pem'
ssh.connect(dns,username='ubuntu',key_filename=key_path)
ssh.exec_command('touch testing')
a,b,c=ssh.exec_command("ls -lah")
print b.readlines()
a,b,c=ssh.exec_command("file = open('/home/ubuntu/hosts', 'w')")
#print b.readlines()
ssh.exec_command("file.write('127.0.0.1 localhost\n')")
for tag,ip in hosts_file_info.iteritems():
ssh.exec_command("file.write('%s %s\n' % (ip,tag))")
ssh.exec_command("file.close()")
ssh.close()
public_dns = 'ec2-xx-xxx-xxx-xxx.compute-1.amazonaws.com'
print public_dns
hosts_file_info = {}
#hosts_file_info['1']='test'
#hosts_file_info['2']='test2'
#hosts_file_info['3']='test3'
#print hosts_file_info
update_hosts_file(public_dns,hosts_file_info)
它看起來像你想,如果他們的bash命令來執行Python語句,比如'文件= open('/ home/ubuntu/hosts','w')'。我不知道這是否會給你一個bash語法錯誤,或'file'像'無法打開「=」(沒有這樣的文件)'一個錯誤,但我相信它不會做任何有用的。 – abarnert
BTW,檢查出布http://docs.fabfile.org/en/1.8/。這使得很多這種自動化方式變得簡單和方便。 –