gpt4 book ai didi

python - 使用 python 自动创建并登录到 linux 虚拟机

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:22:01 25 4
gpt4 key购买 nike

我目前有一个工作的 python 脚本,它通过 SSH 连接到远程 Linux 机器并在该机器上执行命令。我正在使用 paramiko处理 ssh 连接。下面是运行中的代码,执行 hostname -s 命令:

blade = '192.168.1.15'
username='root'
password=''
# now, connect
try:
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.WarningPolicy())
print '*** Connecting...'
client.connect(blade, 22, username, password)
# print hostname for verification
stdin, stdout, stderr = client.exec_command('hostname --short')
print stdout.readlines()
except Exception, e:
print '*** Caught exception: %s: %s' % (e.__class__, e)
traceback.print_exc()
try:
client.close()
except:
pass
sys.exit(1)

这很好用,但我实际上想做的事情要复杂得多。我实际上想做的是 SSH 进入同一台 Linux 机器,就像我上面所做的那样,然后在上面创建一个临时虚拟机,并在该虚拟机上执行命令。这是我的(无效的)尝试:

blade='192.168.1.15'
username='root'
password=''
# now, connect
try:
# client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.WarningPolicy())
print '*** Connecting...'
client.connect(blade, 22, username, password)
# create VM, log in, and print hostname for verification
stdin, stdout, stderr = client.exec_command('sudo kvm -m 1024 -drive file=/var/lib/libvirt/images/oa4-vm$
time.sleep(60) #delay to allow VM to initialize
stdin.write(username + '\n') #log into VM
stdin.write(password + '\n') #log into VM
stdin, stdout, stderr = client.exec_command('hostname --short')
print stdout.readlines()
except Exception, e:
print '*** Caught exception: %s: %s' % (e.__class__, e)
traceback.print_exc()
try:
client.close()
except:
pass
sys.exit(1)

当我运行它时,我得到以下信息:

joe@computer:~$ python automata.py
*** Connecting...
/home/joe/.local/lib/python2.7/site-packages/paramiko/client.py:95: UserWarning: Unknown ssh-rsa host key for 192.168.1.15: 25f6a84613a635f6bcb5cceae2c2b435
(key.get_name(), hostname, hexlify(key.get_fingerprint())))
*** Caught exception: <class 'socket.error'>: Socket is closed
Traceback (most recent call last):
File "automata.py", line 32, in function1
stdin.write(username + '\n') #log into VM
File "/home/joe/.local/lib/python2.7/site-packages/paramiko/file.py", line 314, in write
self._write_all(data)
File "/home/joe/.local/lib/python2.7/site-packages/paramiko/file.py", line 439, in _write_all
count = self._write(data)
File "/home/joe/.local/lib/python2.7/site-packages/paramiko/channel.py", line 1263, in _write
self.channel.sendall(data)
File "/home/joe/.local/lib/python2.7/site-packages/paramiko/channel.py", line 796, in sendall
raise socket.error('Socket is closed')
error: Socket is closed

我不确定如何解释此错误——“套接字已关闭”让我认为 SSH 连接正在终止我尝试创建 VM 的连接。有人有任何指示吗?

更新

我正在尝试使用 pexpect 包装器,但无法让它与 un/pw 提示进行交互。我正在通过 ssh 进入远程机器并运行 test.py 脚本来测试该过程,该脚本提示我输入用户名,然后将用户名保存在文本文件中。这是我的 fab 文件:

env.hosts = ['hostname']
env.user = 'userame'
env.password = 'password'


def vm_create():
run("python test.py")

而远程机器上test.py的内容是:

#! /usr/bin/env python

uname = raw_input("Enter Username: ")

f = open('output.txt','w')
f.write(uname + "\n")
f.close

因此,我可以在本地机器上执行“fab vm_create”,它成功建立了 SSH 连接并提示我输入用户名,如 test.py 所定义。但是,如果我使用 pexpect 包装器在本地计算机上执行第三个 python 文件,如下所示:

import pexpect
child = pexpect.spawn('fab vm_create')
child.expect ('Enter Username: ')
child.sendline ('password')

似乎什么都没有发生。我没有收到任何错误,也没有在远程机器上创建 output.txt。我是否错误地使用了 pexpect?

最佳答案

虽然我很喜欢 paramiko,但它可能更适合使用 Fabric .

这是一个示例 fabfile.py:

from fabric.api import run
from fabric.api import sudo
from fabric.api import env

env.user = 'root'
env.password = ''
env.host = ='192.168.1.15'

def vm_up():
sudo("kvm -m 1024 -drive file=/var/lib/libvirt/images/oa4-vm$...")
run("hostname --short")

然后运行它,使用

$ fab vm_up

如果您没有在 fabfile 本身中设置主机和密码(这是正确的),那么您可以在命令行中设置它们:

$ fab -H 192.168.1.15 -p PASSWORD vm_up

但是,您的 kvm 行仍在等待输入。要发送输入(并等待预期的提示),请编写另一个使用 pexpect 调用 fab 的脚本:

child = pexpect.spawn('fab vm_up')
child.expect('username:') # Put this in the format you're expecting
child.send('root')

关于python - 使用 python 自动创建并登录到 linux 虚拟机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19993381/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com