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
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
run ("ls -ltr")
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.
sys.stderr = open('/dev/null')
ssh = paramiko.SSHClient()
ssh.connect('10.0.0.10', username='root', password='JamesBond')
sftp = ssh.open_sftp()
stdin, stdout, stderr = ssh.exec_command("chmod +x /root/testing.py")
stdin, stdout, stderr = ssh.exec_command("python /root/testing.py")
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 netifaces as nif
for loop_ip in ['10.0.0.2', '10.0.0.6']:
#Will get the hostname and IP address.
dns = socket.gethostbyaddr(loop_ip)
hostnm = dns
ipadd = (", ".join(dns))
print hostnm.ljust(10), ipadd.rjust(20)
except socket.error, msg: