Python으로 ssh를 통해 명령 수행
파이썬에서 일부 명령 줄 명령을 자동화하는 스크립트를 작성 중입니다. 현재 전화를 걸고 있습니다.
cmd = "some unix command"
retcode = subprocess.call(cmd,shell=True)
그러나 원격 컴퓨터에서 일부 명령을 실행해야합니다. 수동으로 ssh를 사용하여 로그인 한 다음 명령을 실행합니다. 파이썬에서 이것을 어떻게 자동화합니까? 원격 컴퓨터에 (알려진) 비밀번호로 로그인해야하므로 사용할 수 없습니다. 사용해야 cmd = ssh user@remotehost
할 모듈이 있는지 궁금합니다.
나는 당신에게 paramiko 를 참조 할 것입니다
볼 이 질문을
ssh = paramiko.SSHClient()
ssh.connect(server, username=username, password=password)
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(cmd_to_execute)
또는 commands.getstatusoutput을 사용할 수 있습니다 .
commands.getstatusoutput("ssh machine 1 'your script'")
광범위하게 사용했으며 훌륭하게 작동합니다.
Python 2.6 이상에서는을 사용하십시오 subprocess.check_output
.
Fabric을 보셨습니까 ? 파이썬을 사용하여 SSH를 통해 모든 종류의 원격 작업을 수행 할 수 있습니다.
나는 paramiko가 너무 낮은 수준이라는 것을 알았고 Fabric은 라이브러리로 사용하기에 특히 적합하지 않았으므로 paramiko를 사용하여 약간 더 멋진 인터페이스를 구현하는 spur 라는 자체 라이브러리 를 구성했습니다.
import spur
shell = spur.SshShell(hostname="localhost", username="bob", password="password1")
result = shell.run(["echo", "-n", "hello"])
print result.output # prints hello
쉘 내부에서 실행해야하는 경우 :
shell.run(["sh", "-c", "echo -n hello"])
모두 paramiko를 사용하여 이미 언급 (권장) 했으며 한 번에 여러 명령을 실행할 수있는 파이썬 코드 (API 하나)를 공유하고 있습니다.
다른 노드에서 명령을 실행하려면 다음을 사용하십시오. Commands().run_cmd(host_ip, list_of_commands)
명령 중 하나라도 실행되지 않으면 실행을 중지 한 TODO가 표시됩니다. 어떻게해야할지 모르겠습니다. 당신의 지식을 공유하십시오
#!/usr/bin/python
import os
import sys
import select
import paramiko
import time
class Commands:
def __init__(self, retry_time=0):
self.retry_time = retry_time
pass
def run_cmd(self, host_ip, cmd_list):
i = 0
while True:
# print("Trying to connect to %s (%i/%i)" % (self.host, i, self.retry_time))
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host_ip)
break
except paramiko.AuthenticationException:
print("Authentication failed when connecting to %s" % host_ip)
sys.exit(1)
except:
print("Could not SSH to %s, waiting for it to start" % host_ip)
i += 1
time.sleep(2)
# If we could not connect within time limit
if i >= self.retry_time:
print("Could not connect to %s. Giving up" % host_ip)
sys.exit(1)
# After connection is successful
# Send the command
for command in cmd_list:
# print command
print "> " + command
# execute commands
stdin, stdout, stderr = ssh.exec_command(command)
# TODO() : if an error is thrown, stop further rules and revert back changes
# Wait for the command to terminate
while not stdout.channel.exit_status_ready():
# Only print data if there is data to read in the channel
if stdout.channel.recv_ready():
rl, wl, xl = select.select([ stdout.channel ], [ ], [ ], 0.0)
if len(rl) > 0:
tmp = stdout.channel.recv(1024)
output = tmp.decode()
print output
# Close SSH connection
ssh.close()
return
def main(args=None):
if args is None:
print "arguments expected"
else:
# args = {'<ip_address>', <list_of_commands>}
mytest = Commands()
mytest.run_cmd(host_ip=args[0], cmd_list=args[1])
return
if __name__ == "__main__":
main(sys.argv[1:])
감사합니다!
I have used paramiko a bunch (nice) and pxssh (also nice). I would recommend either. They work a little differently but have a relatively large overlap in usage.
Keep it simple. No libraries required.
import subprocess
subprocess.Popen("ssh {user}@{host} {cmd}".format(user=user, host=host, cmd='ls -l'), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
paramiko finally worked for me after adding additional line, which is really important one (line 3):
import paramiko
p = paramiko.SSHClient()
p.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # This script doesn't work for me unless this line is added!
p.connect("server", port=22, username="username", password="password")
stdin, stdout, stderr = p.exec_command("your command")
opt = stdout.readlines()
opt = "".join(opt)
print(opt)
Make sure that paramiko package is installed. Original source of the solution: Source
#Reading the Host,username,password,port from excel file
import paramiko
import xlrd
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
loc = ('/Users/harshgow/Documents/PYTHON_WORK/labcred.xlsx')
wo = xlrd.open_workbook(loc)
sheet = wo.sheet_by_index(0)
Host = sheet.cell_value(0,1)
Port = int(sheet.cell_value(3,1))
User = sheet.cell_value(1,1)
Pass = sheet.cell_value(2,1)
def details(Host,Port,User,Pass):
ssh.connect(Host, Port, User, Pass)
print('connected to ip ',Host)
stdin, stdout, stderr = ssh.exec_command("")
stdin.write('xcommand SystemUnit Boot Action: Restart\n')
print('success')
details(Host,Port,User,Pass)
Have a look at spurplus
, a wrapper we developed around spur
that provides type annotations and some minor gimmicks (reconnecting SFTP, md5 etc.): https://pypi.org/project/spurplus/
Works Perfectly...
import paramiko
import time
ssh = paramiko.SSHClient()
#ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('10.106.104.24', port=22, username='admin', password='')
time.sleep(5)
print('connected')
stdin, stdout, stderr = ssh.exec_command(" ")
def execute():
stdin.write('xcommand SystemUnit Boot Action: Restart\n')
print('success')
execute()
Asking User to enter the command as per the device they are logging in.
The below code is validated by PEP8online.com.
import paramiko
import xlrd
import time
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
loc = ('/Users/harshgow/Documents/PYTHON_WORK/labcred.xlsx')
wo = xlrd.open_workbook(loc)
sheet = wo.sheet_by_index(0)
Host = sheet.cell_value(0, 1)
Port = int(sheet.cell_value(3, 1))
User = sheet.cell_value(1, 1)
Pass = sheet.cell_value(2, 1)
def details(Host, Port, User, Pass):
time.sleep(2)
ssh.connect(Host, Port, User, Pass)
print('connected to ip ', Host)
stdin, stdout, stderr = ssh.exec_command("")
x = input('Enter the command:')
stdin.write(x)
stdin.write('\n')
print('success')
details(Host, Port, User, Pass)
Below example, incase if you want user inputs for hostname,username,password and port no.
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
def details():
Host = input("Enter the Hostname: ")
Port = input("Enter the Port: ")
User = input("Enter the Username: ")
Pass = input("Enter the Password: ")
ssh.connect(Host, Port, User, Pass, timeout=2)
print('connected')
stdin, stdout, stderr = ssh.exec_command("")
stdin.write('xcommand SystemUnit Boot Action: Restart\n')
print('success')
details()
참고URL : https://stackoverflow.com/questions/3586106/perform-commands-over-ssh-with-python
'development' 카테고리의 다른 글
RichTextBox (WPF)에는 문자열 속성 "Text"가 없습니다. (0) | 2020.07.27 |
---|---|
EditorFor () 및 html 속성 (0) | 2020.07.27 |
일치하지 않는 익명의 define () 모듈 (0) | 2020.07.26 |
양식 제출 후 Jquery 콜백을 수행하는 방법은 무엇입니까? (0) | 2020.07.26 |
JNA 대신 JNI를 사용하여 기본 코드를 호출 하시겠습니까? (0) | 2020.07.26 |