Programing

Python을 사용하여 SSH를 사용하는 가장 간단한 방법은 무엇입니까?

lottogame 2020. 10. 12. 07:04
반응형

Python을 사용하여 SSH를 사용하는 가장 간단한 방법은 무엇입니까?


로컬 Python (3.0) 스크립트에서 원격 서버에 SSH하고 로그인 / 암호를 제공하고 명령을 실행하고 출력을 Python 콘솔에 인쇄하려면 어떻게해야합니까?

큰 외부 라이브러리를 사용하지 않거나 원격 서버에 아무것도 설치하지 않습니다.


나는 그것을 시도하지 않았지만이 pysftp 모듈이 도움 될 수 있으며 차례로 paramiko를 사용합니다. 나는 모든 것이 클라이언트 측이라고 믿습니다.

흥미로운 명령은 아마도 .execute()원격 시스템에서 임의의 명령을 실행하는 입니다. (이 모듈은 또한 FTP 문자를 더 많이 암시하는 기능 .get().put방법을 제공합니다).

최신 정보:

원래 링크 한 블로그 게시물을 더 이상 사용할 수 없게 된 후 답변을 다시 작성했습니다. 이 답변의 이전 버전을 참조하는 일부 댓글은 이제 이상하게 보입니다.


위에서 제안한대로 Paramiko를 사용하여 직접 코딩 할 수 있습니다. 또는 요청한 모든 작업을 수행하는 Python 애플리케이션 인 Fabric을 살펴볼 수 있습니다.

Fabric은 애플리케이션 배포를 간소화하거나 SSH 프로토콜을 통해 시스템 관리 작업을 수행하도록 설계된 Python 라이브러리 및 명령 줄 도구입니다. 임의의 셸 명령 (일반 로그인 사용자로 또는 sudo를 통해) 실행, 파일 업로드 및 다운로드 등을위한 도구를 제공합니다.

나는 이것이 당신의 필요에 맞다고 생각합니다. 또한 클라이언트에 설치해야하는 paramiko 및 pycrypt에 대한 종속성이 있지만 큰 라이브러리가 아니며 서버 설치가 필요하지 않습니다.

이 앱은 여기에 있었습니다. 이제 여기 에서 찾을 수 있습니다 .

* The official, canonical repository is git.fabfile.org
* The official Github mirror is GitHub/bitprophet/fabric

몇 가지 좋은 기사가 있지만 지난 6 개월 동안 변경되었으므로주의해야합니다.

Fabric으로 Django 배포

최신 Python 해커의 도구 : Virtualenv, Fabric 및 Pip

Fabric 및 Virtualenv를 통한 간단하고 쉬운 배포


나중에 : Fabric을 설치하는 데 더 이상 paramiko가 필요하지 않습니다.

$ pip install fabric
Downloading/unpacking fabric
  Downloading Fabric-1.4.2.tar.gz (182Kb): 182Kb downloaded
  Running setup.py egg_info for package fabric
    warning: no previously-included files matching '*' found under directory 'docs/_build'
    warning: no files found matching 'fabfile.py'
Downloading/unpacking ssh>=1.7.14 (from fabric)
  Downloading ssh-1.7.14.tar.gz (794Kb): 794Kb downloaded
  Running setup.py egg_info for package ssh
Downloading/unpacking pycrypto>=2.1,!=2.4 (from ssh>=1.7.14->fabric)
  Downloading pycrypto-2.6.tar.gz (443Kb): 443Kb downloaded
  Running setup.py egg_info for package pycrypto
Installing collected packages: fabric, ssh, pycrypto
  Running setup.py install for fabric
    warning: no previously-included files matching '*' found under directory 'docs/_build'
    warning: no files found matching 'fabfile.py'
    Installing fab script to /home/hbrown/.virtualenvs/fabric-test/bin
  Running setup.py install for ssh
  Running setup.py install for pycrypto
...
Successfully installed fabric ssh pycrypto
Cleaning up...

그러나 이것은 대부분 외형 적이지만 ssh는 paramiko의 포크이고 두 라이브러리의 관리자는 동일하며 (Fabric의 저자 인 Jeff Forcier) 관리자는 paramiko라는 이름으로 paramiko와 ssh를 재결합 할 계획을 가지고 있습니다. (이 수정은 pbanka 를 통해 이루어집니다 .)


추가 모듈을 피하려면 하위 프로세스 모듈을 사용하여 다음을 실행할 수 있습니다.

ssh [host] [command]

출력을 캡처합니다.

다음과 같이 시도하십시오.

process = subprocess.Popen("ssh example.com ls", shell=True,
    stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output,stderr = process.communicate()
status = process.poll()
print output

사용자 이름과 암호를 처리하기 위해 하위 프로세스를 사용하여 ssh 프로세스와 상호 작용하거나 서버에 공개 키를 설치하여 암호 프롬프트를 피할 수 있습니다.


libssh2에 대한 Python 바인딩을 작성했습니다 . Libssh2는 SSH2 프로토콜을 구현하는 클라이언트 측 라이브러리입니다.

import socket
import libssh2

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('exmaple.com', 22))

session = libssh2.Session()
session.startup(sock)
session.userauth_password('john', '******')

channel = session.channel()
channel.execute('ls -l')

print channel.read(1024)

여기서 "가장 간단한"정의가 중요합니다. 간단한 코드는 모듈을 사용하는 것을 의미합니다 ( "대형 외부 라이브러리"는 과장된 것임).

나는 가장 최신 (능동적으로 개발 된) 모듈이 paramiko 라고 믿는다 . 다운로드시 데모 스크립트와 함께 제공되며 자세한 온라인 API 문서가 있습니다. pexpect 에 포함 된 PxSSH사용해 볼 수도 있습니다 . 첫 번째 링크에는 설명서와 함께 간단한 샘플이 있습니다.

다시 한 번 단순함과 관련하여 좋은 오류 감지는 항상 코드를 더 복잡하게 보이게 만들지 만 샘플 스크립트에서 많은 코드를 재사용 한 다음 잊어 버릴 수 있어야합니다.


휴드 브라운처럼 저는 패브릭을 좋아합니다. 자체 선언적 스크립팅 (배포 등을위한)을 구현하는 동안 Python 모듈로 가져와 Fabric 스크립트를 작성하지 않고도 프로그램에서 사용할 수도 있습니다.

Fabric은 새로운 메인테이너를 가지고 있으며 재 작성 중입니다. 즉, (현재) 웹에서 찾을 수있는 대부분의 자습서는 현재 버전에서 작동하지 않습니다. 또한 Google은 여전히 ​​첫 번째 결과로 이전 Fabric 페이지를 표시합니다.

최신 문서는 http://docs.fabfile.org에서 확인할 수 있습니다.


I found paramiko to be a bit too low-level, and Fabric not especially well-suited to being used as a library, so I put together my own library called spur that uses paramiko to implement a slightly nicer interface:

import spur

shell = spur.SshShell(hostname="localhost", username="bob", password="password1")
result = shell.run(["echo", "-n", "hello"])
print result.output # prints hello

You can also choose to print the output of the program as it's running, which is useful if you want to see the output of long-running commands before it exits:

result = shell.run(["echo", "-n", "hello"], stdout=sys.stdout)

For benefit of those who reach here googling for python ssh sample. The original question and answer are almost a decode old now. It seems that the paramiko has gain a bit of functionalities (Ok. I'll admit - pure guessing here - I'm new to Python) and you can create ssh client directly with paramiko.

import base64
import paramiko

client = paramiko.SSHClient()

client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('192.168.1.1', username='user', password='password')
stdin, stdout, stderr = client.exec_command('cat /proc/meminfo')
for line in stdout:
    print('... ' + line.strip('\n'))
client.close()

This code was adapted from demo of https://github.com/paramiko/paramiko It works for me.


This worked for me

import subprocess
import sys
HOST="IP"
COMMAND="ifconfig"

def passwordless_ssh(HOST):
        ssh = subprocess.Popen(["ssh", "%s" % HOST, COMMAND],
                       shell=False,
                       stdout=subprocess.PIPE,
                       stderr=subprocess.PIPE)
        result = ssh.stdout.readlines()
        if result == []:
                error = ssh.stderr.readlines()
                print >>sys.stderr, "ERROR: %s" % error
                return "error"
        else:
                return result

please refer to paramiko.org, its very useful while doing ssh using python.

import paramiko

import time

ssh = paramiko.SSHClient() #SSHClient() is the paramiko object

'''Below lines adds the server key automatically to know_hosts file.use anyone one of the below'''

ssh.load_system_host_keys()

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

try:

Here we are actually connecting to the server.

ssh.connect('10.106.104.24', port=22, username='admin', password='')

time.sleep(5)

I have mentioned time because some servers or endpoint prints there own information after loggin in e.g. the version, model and uptime information, so its better to give some time before executing the command.

Here we execute the command, stdin for input, stdout for output, stderr for error

stdin, stdout, stderr = ssh.exec_command('xstatus Time')

Here we are reading the lines from output.

output = stdout.readlines() 

print(output)

Below all are the Exception handled by paramiko while ssh. Refer to paramiko.org for more information about exception.

except (BadHostKeyException, AuthenticationException,
SSHException, socket.error) as e:

print(e)

Have a look at spurplus, a wrapper around spur and paramiko that we developed to manage remote machines and perform file operations.

Spurplus provides a check_output() function out-of-the-box:

import spurplus
with spurplus.connect_with_retries(
        hostname='some-machine.example.com', username='devop') as shell:
     out = shell.check_output(['/path/to/the/command', '--some_argument']) 
     print(out)

참고URL : https://stackoverflow.com/questions/1233655/what-is-the-simplest-way-to-ssh-using-python

반응형