Sometimes, we need to run a simple command on a remote machine over SSH. For example, we need to query the remote machine's CPU or RAM information. This can be done from a Python script as shown in this recipe.
You need to install the third-party package, Paramiko
, as shown in the following command, from the source available from GitHub's repository at https://github.com/paramiko/paramiko:
$ pip install paramiko
We can use the paramiko
module to create a remote session to a Unix machine.
Then, from this session, we can read the remote machine's /proc/cpuinfo
file to extract the CPU information.
Listing 7.3 gives the code for printing a remote machine's CPU information, as follows:
#!/usr/bin/env python # Python Network Programming Cookbook -- Chapter - 7 # This program is optimized for Python 2.7. # It may run on any other version with/without modifications. import argparse import getpass import paramiko RECV_BYTES = 4096 COMMAND = 'cat /proc/cpuinfo' def print_remote_cpu_info(hostname, port, username, password): client = paramiko.Transport((hostname, port)) client.connect(username=username, password=password) stdout_data = [] stderr_data = [] session = client.open_channel(kind='session') session.exec_command(COMMAND) while True: if session.recv_ready(): stdout_data.append(session.recv(RECV_BYTES)) if session.recv_stderr_ready(): stderr_data.append(session.recv_stderr(RECV_BYTES)) if session.exit_status_ready(): break print 'exit status: ', session.recv_exit_status() print ''.join(stdout_data) print ''.join(stderr_data) session.close() client.close() if __name__ == '__main__': parser = argparse.ArgumentParser(description='Remote file copy') parser.add_argument('--host', action="store", dest="host", default='localhost') parser.add_argument('--port', action="store", dest="port", default=22, type=int) given_args = parser.parse_args() hostname, port = given_args.host, given_args.port username = raw_input("Enter the username:") password = getpass.getpass("Enter password for %s: " %username) print_remote_cpu_info(hostname, port, username, password)
Running this script will show the CPU information of a given host, in this case, the local machine, as follows:
$ python 7_3_print_remote_cpu_info.py Enter the username:faruq Enter password for faruq: exit status: 0 processor : 0 vendor_id : GenuineIntel cpu family : 6 model : 42 model name : Intel(R) Core(TM) i5-2400S CPU @ 2.50GHz stepping : 7 cpu MHz : 2469.677 cache size : 6144 KB fdiv_bug : no hlt_bug : no f00f_bug : no coma_bug : no fpu : yes fpu_exception : yes cpuid level : 5 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 syscall nx rdtscp lm constant_tsc up pni monitor ssse3 lahf_lm bogomips : 4939.35 clflush size : 64 cache_alignment : 64 address sizes : 36 bits physical, 48 bits virtual power management:
First, we collect the connection parameters such as hostname, port, username, and password. These parameters are then passed to the
print_remote_cpu_info()
function.
This function creates an SSH client session by calling the transport
class of paramiko
. The connection is made thereafter using the supplied username and password. We can create a raw communication session using open_channel()
on the SSH client. In order to execute a command on the remote host, exec_command()
can be used.
After sending the command to the remote host, the response from the remote host can be caught by blocking the recv_ready()
event of the session object. We can create two lists, stdout_data
and stderr_data
, and use them to store the remote output and error messages.
When the command exits in the remote machine, it can be detected using the exit_status_ready()
method, and the remote session data can be concatenated using the join()
string method.
Finally, the session and client connection can be closed using the close()
method on each object.
18.220.181.146