Paramiko with SSH-Keys

Paramiko bukan hanya sebuah module untuk melakukan SSH ke perangkat jaringan. tetapi bisa kedalam sebuah standard server. paramiko dapat menggunakan SSH key untuk masuk selain menggunakan password. pertama, generate key di server python.

ubuntu@ubuntu:~$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/ubuntu/.ssh/id_rsa): 
Created directory '/home/ubuntu/.ssh'.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/ubuntu/.ssh/id_rsa.
Your public key has been saved in /home/ubuntu/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:WY7Ejx0t7B5J/kwmXA72QFVagbkqVpeGXfgkMaaMbow ubuntu@ubuntu
The key's randomart image is:
+---[RSA 2048]----+
|          ..=*+. |
|       . = +=+o  |
|        + %o+B   |
|       = #oX* .  |
|      E S.@+=    |
|       .o..B     |
|       . .. o    |
|                 |
|                 |
+----[SHA256]-----+
ubuntu@ubuntu:~$ cat .ssh/id_rsa.pub
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDByQCm4EoUysOguza03n/FYdvfCKn/zMzVMin7saoWmdMnV05MTGjn4rB8XZigsC2UNMfVikfKcH0owGTuXZjMQtKaidxQkMGNZxEZPKyT9kXRfPrdSTAcbi0Flq4daHQils3cLrOd3O2F4Q2XFEI5U24rlOupTgvhpTVjpNl+++ha31oQ/3iNmeHzVe1HjyzZMxeqoOGLqciSw/MbaMVq+pTnz14nkcjuYB6FtNGcPfp6e51lnY/rfIIEwTdbddKzG0DtPplXpZJGhLeelRV+K5FAut+qF8hbMcfEb8922LPy93F0kq3CeW3UPgMB0hGcOQhXF5O66qkOcdsnia8j ubuntu@ubuntu

copykan public key yang digenerate kedalam directory user (file authorized_keys) yang diinginkan (root atau user biasa) di server yang ingin diotomasi :

root@ubuntu:~# mkdir .ssh/
root@ubuntu:~# nano .ssh/authorized_keys

buat program

import sys
import time
import paramiko

host = str(sys.argv[1])
port = int(sys.argv[2])
user = str(sys.argv[3])

# Create Session
session = paramiko.SSHClient()

# get private key from user
key = paramiko.RSAKey.from_private_key_file('/home/ubuntu/.ssh/id_rsa')

# set policy when connecting to server with unknown host key and add hostname & key to known_hosts
session.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# Connect to Server
session.connect(host, username=user, port=port, pkey=key)

# invoke a shell
shell = session.invoke_shell()

# send command to device
shell.send("pwd")

# add time to be able to load all data
time.sleep(1)

# receive data in maximal 5000 bytes
output = shell.recv(5000)

# print the output
print(output)

# close the session
shell.close()

jalankan program tersebut

ubuntu@ubuntu:~/paramiko$ python lab2.py "192.168.122.60" 22 "root"
Welcome to Ubuntu 16.04.4 LTS (GNU/Linux 4.4.0-116-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

99 packages can be updated.
47 updates are security updates.


Last login: Fri Jul 13 10:13:20 2018 from 192.168.122.129
pwdroot@ubuntu:~# pwd
ubuntu@ubuntu:~/paramiko$

Comments are closed.