0

I am trying to make script to ssh my device with r/o user and then super user and execute a command.Below are the steps i did on my putty

  1. login as admin ( r/o user) and password.
  2. sudo su and than password
  3. execute a command
  4. print output of executed command

i tried below code to make it working but i didn't get any output.

import paramiko
import pandas as pd
import openpyxl
from paramiko import AuthenticationException
from paramiko.ssh_exception import SSHException, NoValidConnectionsError
import socket
import time
import os
import inspect
import datetime

start = time.time()
print("Starting................................Please Wait") 
df=pd.DataFrame(columns=["ip","Status","Remarks"])
ips = ['10.11.8.71']

root = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))

#ips = open (root+ "/440_ip.txt")
for ipp in ips:
              ip = ipp.strip()
        port=22
        username='admin'
        #password='AeGEBUx66m_1ND'
        #cmd='interface wireless set [ find default-name=wlan1 ] ampdu-priorities=0,1,2,3,4,5,6,7 rate-set=configured rx-chains=0,1 scan-list=5825-5875 security-profile=iB440 ssid=iBw supported-rates-a/g="" basic-rates-a/g=""' 
        ssh=paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        
        ssh.connect(ip,port,username,timeout=5,password='HeWGEUx66m=_4!ND')
        
        stdin, stdout, stderr = ssh.exec_command('sudo bash', get_pty = True)
        time.sleep(0.1)
        stdin.write('HeWGEUx66m=_4!ND\n')
        stdin.flush()
        stdin.write('whoami\n')
        #time.sleep(1)

        
        stdin.flush()
        dd = stdout.readlines()
        print(dd)
        ssh.close()

After running the code there is no error, seems it stuck in some loop.,

Starting................................Please Wait

enter image description here

Using ssh with plink in single line command

C:\Users\Administrator\AppData\Local\Programs\Python\Python38>plink.exe -ssh -t admin@10.11.8.71 sudo bash admin@10.11.8.71's password: Access granted. Press Return to begin session. Password: bash-3.2# whoami root bash-3.2#```



Sonu
  • 314
  • 2
  • 9
  • @MartinPrikryl i already tried that but didn't work for me, please help on this. – Sonu Sep 14 '20 at 18:45
  • yes i tried print(stdout.read()) after (exec_command) but still seems stuck in loop. – Sonu Sep 15 '20 at 06:45
  • same happening with stderr, i have updated the results of ssh admin@10.11.8.71 sudo bash. For my script to be be working, i need to do sudo bash and after that need to run some commands. – Sonu Sep 15 '20 at 07:18
  • Edit this into your question please + Remove the `ssh.invoke_shell()`. – Martin Prikryl Sep 15 '20 at 07:33
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/221496/discussion-between-sunil-sharma-and-martin-prikryl). – Sonu Sep 15 '20 at 07:39

1 Answers1

1

To make it working properl i used channels from paramiko, and it worked like charm.

import paramiko
from paramiko import *
from paramiko.channel import Channel
import time
import os
import inspect
import datetime
from socket import *
import pandas as pd

df = pd.DataFrame(columns=["Ip","Status",'Remarks'])
root = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))

#ips = ['10.23.0.30', '10.23.0.11','10.23.0.12','10.23.0.13']

ips = open(root+ "\\ahip.txt")                           
for ipp in ips:
   ip = ipp.strip()                        
                           
   print(ip)
   ssh = paramiko.SSHClient()
   ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
   try:
      ssh.connect(ip, port=22,timeout = 5,username='op', password='C#Uj!AnX')
   channel:Channel = ssh.invoke_shell()
      #print(type(channel))
      channel_data = str()
      while True:
         #channel.recv_ready():
         #time.sleep(1)
         channel_data += str(channel.recv(999))
         

         channel.send("su -\n")
         time.sleep(1)
            #channel_data += str(channel.recv(999))

            # if "Password" in channel_data:
         channel.send("HeWGEUx\n")
         time.sleep(3)
            #channel_data += str(channel.recv(999))

         channel.send("/bs/lteCli\n")
         time.sleep(3)

         channel.send("logger threshold set cli=6\n")
         time.sleep(4)

         channel.send("db set stackCfg [1] EnCLPC=0\n")
         time.sleep(4)
         
         channel.send("db get stackCfg EnCLPC\n")
         time.sleep(3)

            #channel.send("db get stackCfg EnCLPC\n")
         time.sleep(.1)

         channel_data  += str(channel.recv(99999))
         str2 = 'Done'
         df.loc[ip]=[ip,str2,channel_data]
         #print(channel_data)
         channel.close()
         ssh.close()
         break
         
   except (timeout ,AuthenticationException):
         print(ip+'not done')
         str1 = 'Not Done'
         df.loc[ip]=[ip,'failed',str1]

Sonu
  • 314
  • 2
  • 9