2017-08-20 4 views
0

Je travaille sur un projet qui pique des périphériques LAN et écrit l'avg_time prise par le ping dans une base de données MySQL.Utilisation de sudo en script python

# Python script to update contents of MySQL database 

import MySQLdb 
import subprocess 
import re 

#Connecting to MySQL database 
db = MySQLdb.connect("localhost","tempLocal","thunderbolt","dbavgspeed") 
#initializing cursor 
cur = db.cursor() 

error = "Request" 

while 1: 
    # 0.1 is the interval between pings and 4 is the number of times ping operation is performed and -t 1 sets the timeout to 1 sec 
    command1 = ['ping','-n','-i','0.1','-t','1','-c','400','192.168.1.1'] 
    p1 = subprocess.Popen(command1,stdout=subprocess.PIPE) 
    #text is the string which stores the output from the terminal 
    text1 = p1.stdout.read() 


    if error in text1: 
     status1 = 0 
     cur.execute("""UPDATE tbavgspeed SET status = %s WHERE id = %s""",(status1,1)) 
     db.commit() 
    else: 
     status1 = 1 

     find11 = re.search("stddev(.+?)ms", text1) 
     allValues1 = find11.group(1) 
     find12 = re.search("/(.+?)/", allValues1) 
     avgTime1 = find12.group(1) 

     cur.execute("""UPDATE tbavgspeed SET avg_time = %s, status = %s WHERE id = %s""",(avgTime1,status1,1)) 
     db.commit() 

#terminates the connection 
db.close() 
  • Le script fonctionne très bien avec simple commande ping, mais comment ping-je utiliser contre les inondations (ping -f) à travers un script python qui nécessite sudo
  • Y at-il une meilleure façon de calculer les données actuelles taux de transfert pour un routeur
+1

Essayez d'exécuter votre script python en mode super-utilisateur: 'python ...' sudo –

Répondre

1

Vous pouvez exécuter votre script Python avec sudo. Par exemple:

import os 
os.system('ping -f google.com') 

Sans sudo:

$ python 
>>> import os 
>>> os.system('ping -f google.com') 
ping: -f flag: Operation not permitted 
19712 

Avec sudo:

$ sudo python 
>>> import os 
>>> os.system('ping -f google.com') 
PING google.com (172.217.6.78): 56 data bytes 
.^C 
--- google.com ping statistics --- 
409 packets transmitted, 408 packets received, 0.2% packet loss 
round-trip min/avg/max/stddev = 3.334/3.645/9.459/0.362 ms 
0