Python – Fabric: Connect to a remote server and execute few simple commands.

Fabric is a Python module used to connect to remote servers with SSH and execute various commands. The script below provides the IP for the server to connect to along with the username and password. Then a function is defined with the commands we wish to execute. We execute the script by typing the following command. It provides the name of the file and it also calls the function we defined.

fab -f testin.py uptime
#!/usr/bin/python
from fabric.api import *

env.use_ssh_config = False
env.hosts = ["10.0.0.20"]
env.user = "root"
#env.key_filename = "/root/.ssh/id_rsa"
env.password = "Password!"
env.port = 22


def uptime():
        run("uptime")
        run ("ls -ltr")
        
Share Button

Python – Paramiko module

Paramiko is a Python module that is used to remotely connect via SSH to remote servers and execute commands on that server. The script below connects to a remote server with the username and password provided in order to transfer a file. It also changes the permissions of the file transferred.

import sys
import paramiko
sys.stderr = open('/dev/null')  
import psutil

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

ssh.connect('10.0.0.10', username='root', password='JamesBond')
sftp = ssh.open_sftp()
sftp.put('/home/Batman/Documents/python/scripts/testing.py', '/root/testing.py')
stdin, stdout, stderr = ssh.exec_command("chmod +x /root/testing.py")
stdin, stdout, stderr = ssh.exec_command("python /root/testing.py")

print stdout.channel.recv(1024)

ssh.close()
Share Button

Python – Get hostname and IP from remote hosts.

The script resolved IPs to hostnames and matches the IP with the hostname. The script is meant for inventory purposes.

#!/usr/bin/python
from netaddr import IPNetwork
import socket
import netifaces as nif



for loop_ip in ['10.0.0.2', '10.0.0.6']:

    try:
        #Will get the hostname and IP address.
            dns = socket.gethostbyaddr(loop_ip)
            hostnm = dns[0]
            ipadd  = (", ".join(dns[2]))
            print hostnm.ljust(10), ipadd.rjust(20)
        

    except socket.error, msg:
            print msg
Ooutput
win8.sfentona.lol             10.0.0.2
ad1.sfentona.lol             10.0.0.6
Share Button