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 uptime
from fabric.api import *

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

def 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.connect('', username='root', password='JamesBond')
sftp = ssh.open_sftp()
sftp.put('/home/Batman/Documents/python/scripts/', '/root/')
stdin, stdout, stderr = ssh.exec_command("chmod +x /root/")
stdin, stdout, stderr = ssh.exec_command("python /root/")


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.

from netaddr import IPNetwork
import socket
import netifaces as nif

for loop_ip in ['', '']:

        #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
Share Button