Rebooting 3ea Pi4 using netmiko - raspberry-pi

from netmiko import ConnectHandler
ip_num=['192.168.0.101','192.168.0.102','192.168.0.103']
for i in ip_num:
pi4 = {
'device_type':'linux',
'ip' : i,
'username' : 'pi',
'password' : '12345678',
'secret' : 'True',
'port' : '22'
}
net_connect = ConnectionHandler(**pi4)
net_connect.enable()
net_connect.send_command("sudo reboot")
net_connect.disconnect()
this is my code.
The first pi 4 reboots fine. After that I get a readtimeout error. I also want the next 2 devices to reboot.

Without traceback it is hard to be sure, but most likely send_command cannot verify the execution of the command. Try send_command("sudo reboot", cmd_verify=False).
https://ktbyers.github.io/netmiko/docs/netmiko/index.html

Related

Is there a way for me to duplicate my pymodbus server so that they can run in along side eachother without crashing?

I am new to modbus and pymodbus in general, this is the code i have written and it seems to run fine! for my project i would like to duplicate this code somehow and make it possible for them to run along side eachother without crashing.
For the end-user it should be as simple as this:
program:"how many servers would you like to run"
user: "3"
program "what are the adress and count of server 1"
user: "...."
program "what are the adress and count of server 2"
user: "...."
program "what are the adress and count of server 3"
user: "...."
and then they all run and it is possible to get updates alongside the program.
Here is the code i have written up until now:
import pymodbus
from pymodbus.version import version
from pymodbus.server.sync import StartSerialServer
from pymodbus.device import ModbusDeviceIdentification
from pymodbus.datastore import ModbusSequentialDataBlock
from pymodbus.datastore import ModbusSlaveContext, ModbusServerContext
from pymodbus.transaction import ModbusRtuFramer
from pymodbus.constants import Defaults
from pymodbus.client.sync import ModbusSerialClient as modclient
#import logging
#FORMAT = ('%(asctime)-15s %(threadName)-15s' ' %(levelname)-8s %(module)-15s:%(lineno)-8s % (message)s')
#logging.basicConfig(format=FORMAT)
#log = logging.getLogger()
#log.setLevel(logging.DEBUG)
store = ModbusSlaveContext(
di=ModbusSequentialDataBlock(0, [17] * 100), # adresse, verdi( di = digital inputs)
co=ModbusSequentialDataBlock(0, [17] * 100), # --_-- (Coils)
hr=ModbusSequentialDataBlock(0, [17] * 100), # --_-- (Holding registers)
ir=ModbusSequentialDataBlock(0, [17] * 100)) # --_-- (input registers)
identity = ModbusDeviceIdentification()
identity.VendorName = 'Pymodbus'
identity.ProductCode = 'PM'
identity.VendorUrl = 'http://github.com/riptideio/pymodbus/'
identity.ProductName = 'Pymodbus Server'
identity.ModelName = 'Pymodbus Server'
identity.MajorMinorRevision = version.short()
context = ModbusServerContext(slaves=store, single=True)
client = modclient(method="rtu",
port="COM2",
timeout=1000,
stopbits=1,
bytesize= 8,
parity= "N",
baudrate=9600)
client.connect()
while True: #kopier og send in
#input_reg = client.read_holding_registers(address=0,count=0,unit=0)
#co_reg = client.read_coils(address=, count=, unit=)
holding_reg = client.read_holding_registers(address=0,count=8,unit=1) #for addressen 1 osv
print(holding_reg)
#reg_read = holding_reg.registers[2] #leser tredje verdi i arrayet
This is what i get in my terminal when i run it: (the error happens if i dont send a value to it)
WriteRegisterResponse 0 => 6
WriteRegisterResponse 0 => 6
WriteRegisterResponse 0 => 6
Modbus Error: [Input/Output] No Response received from the remote unit/Unable to decode response
WriteRegisterResponse 0 => 6

BackUp Odoo 8 Windows erreur zero size file

I make a specific development of the db_backup openerp 7 module to running on version 8 Odoo.
So it is properly installed and it does backup
the problem is that the sql file size is zero KB
this is the code backup_scheduler.py
import xmlrpclib
import socket
import os
import time
import base64
from openerp.osv import fields,osv,orm
from openerp import tools, netsvc
from openerp.tools.translate import _
import logging
_logger = logging.getLogger(__name__)
def execute(connector, method, *args):
res = False
try:
res = getattr(connector,method)(*args)
except socket.error,e:
raise e
return res
addons_path = tools.config['addons_path'] + '/auto_backup/DBbackups'
class db_backup(osv.Model):
_name = 'db.backup'
def get_db_list(self, cr, user, ids, host='localhost', port='8069', context={}):
uri = 'http://' + host + ':' + port
conn = xmlrpclib.ServerProxy(uri + '/xmlrpc/db')
db_list = execute(conn, 'list')
return db_list
_columns = {
'host' : fields.char('Host', size=100, required='True'),
'port' : fields.char('Port', size=10, required='True'),
'name' : fields.char('Database', size=100, required='True',help='Database you want to schedule backups for'),
'bkp_dir' : fields.char('Backup Directory', size=100, help='Absolute path for storing the backups', required='True')
}
_defaults = {
'bkp_dir' : lambda *a : addons_path,
'host' : lambda *a : 'localhost',
'port' : lambda *a : '8069'
}
def _check_db_exist(self, cr, user, ids):
for rec in self.browse(cr,user,ids):
db_list = self.get_db_list(cr, user, ids, rec.host, rec.port)
if rec.name in db_list:
return True
return False
_constraints = [
(_check_db_exist, _('Error ! No such database exists!'), [])
]
def schedule_backup(self, cr, user, context={}):
conf_ids= self.search(cr, user, [])
confs = self.browse(cr,user,conf_ids)
for rec in confs:
db_list = self.get_db_list(cr, user, [], rec.host, rec.port)
if rec.name in db_list:
try:
if not os.path.isdir(rec.bkp_dir):
os.makedirs(rec.bkp_dir)
except:
raise
bkp_file='%s_%s.sql' % (rec.name, time.strftime('%Y%m%d_%H_%M_%S'))
file_path = os.path.join(rec.bkp_dir,bkp_file)
fp = open(file_path,'wb')
uri = 'http://' + rec.host + ':' + rec.port
conn = xmlrpclib.ServerProxy(uri + '/xmlrpc/db')
bkp=''
try:
bkp = execute(conn, 'dump', tools.config['admin_passwd'], rec.name)
except:
logger.notifyChannel('backup', netsvc.LOG_INFO, "Could'nt backup database %s. Bad database administrator password for server running at http://%s:%s" %(rec.name, rec.host, rec.port))
continue
bkp = base64.decodestring(bkp)
fp.write(bkp)
fp.close()
else:
logger.notifyChannel('backup', netsvc.LOG_INFO, "database %s doesn't exist on http://%s:%s" %(rec.name, rec.host, rec.port))
db_backup()
This is probably because an error occurs on the backend that does not get propagated back to the client. If you check the server logs at the time you take a backup you will probably see the issue.
Note If you need a script to get a backup from or restore a database to a v7, v8 or v9 server take a look at https://github.com/daramousk/odoo_remote_backup
I have developed a script for this specific reason which you can use or change to resolve your issue.

google-api-client suddenly comes back with "invalid request"

I've been running Ruby scripts for weeks now using a Service Account, but today I'm getting an "Invalid Request" when I try to build the client using the following function:
def build_client(user_email)
client = Google::APIClient.new
client.authorization = Signet::OAuth2::Client.new(
:token_credential_uri => 'https://accounts.google.com/o/oauth2/token',
:audience => 'https://accounts.google.com/o/oauth2/token',
:scope => 'https://www.googleapis.com/auth/calendar',
:issuer => SERVICE_ACCOUNT_EMAIL,
:signing_key => Google::APIClient::KeyUtils.load_from_pkcs12(SERVICE_ACCOUNT_PKCS12_FILE_PATH, "notasecret"),
:person => user_email
)
client.authorization.fetch_access_token!
return client
end
Is there a lifespan on Service Accounts? I tried creating another Service Account and using that but I get the same result:
Authorization failed. Server message: (Signet::AuthorizationError)
{
"error" : "invalid_request"
}
Stumped!
OK. I figured it out. It was all to do with the user_email. I was reading it from a file and forgot to chomp the linefeed off, so it was objecting to a mal-formed email address.

Resque Workers on Heroku locked out of Postgres DB SSL- no fix yet

I'm using resque/redis on heroku to send emails as a background job. It works fine for the first email I send, but after that I get the error: (ActiveRecord::StatementInvalid: PG::Error: SSL error: decryption failed or bad record mac :) ...
I've seen the other questions/answers that say to add to an initializer:
Resque.after_fork = Proc.new { ActiveRecord::Base.establish_connection }
OR
Resque.before_fork = Proc.new { ActiveRecord::Base.establish_connection }
However, I have done this (and tried any other thing I can think of) and I'm still getting the same error. I have run the code with only before_fork and only after_fork to no avail.
I am also using APN_sender to send apple push notifications. The workers for these have had no problems (but I'm calling default Heroku workers to do these rather than Resque workers).
Here are my relevant files, please help! This is my first SO question as well.. apologies if it's not done perfectly.
#config/resque.rb
after_fork do |server, worker, resque|
logger.info("Got to after_fork in resque.rb config file")
defined?(ActiveRecord::Base) and
ActiveRecord::Base.establish_connection
end
--------------------
#config/initializers/resque.rb
require 'resque'
require 'resque/server'
heroku_environments = ["staging", "production"]
rails_root = ENV['RAILS_ROOT'] || File.dirname(__FILE__) + '/../..'
rails_env = ENV['RAILS_ENV'] || 'development'
#confusing wording.. determines whether or not we are in Production, tested and working
unless heroku_environments.include?(rails_env)
resque_config = YAML.load_file(rails_root + '/config/resque.yml')
Resque.redis = resque_config[rails_env]
else
uri = URI.parse(ENV["REDISTOGO_URL"] || "redis://localhost:6379/")
Resque.redis = Redis.new(:host => uri.host, :port => uri.port, :password => uri.password)
end
----------------------
#resque.rake
require 'resque/tasks'
task "resque:setup" => :environment do
ENV['QUEUE'] = '*'
Resque.after_fork = Proc.new { ActiveRecord::Base.establish_connection }
Resque.before_fork = Proc.new { ActiveRecord::Base.establish_connection }
end
task "apn:setup" => :environment do
ENV['QUEUE'] = '*'
end
desc "Alias for resque:work (To run workers on Heroku)"
task "jobs:work" => "resque:work"
desc "Alias for apn:work (To run workers on Heroku)"
task "jobs:work" => "apn:work"
-----------------------
#Sending the email
#event.guests.each do |g|
Resque.enqueue(MailerCallback, "Notifier", :time_change, #event.id, g.id)
end
I am running one Heroku worker and one Resque worker from the Heroku ps:scale command. As I said, the first email sends error-free, and then any emails after get the above error.
Thanks in advance!
Mike
OK, so couldn't figure this out...
Switched over to delayed job and it's working much better. A little frustrating that I can't send push notifications with apn_sender anymore, but apn_on_rails is working fine.
Weird problem, still curious...

In remote host: Connection could not be established with host smtp.gmail.com [Connection timed out #110]

after deploying I gettin this error below when i try to send an mail:
500 | Internal Server Error | Swift_TransportException
Connection could not be established with host smtp.gmail.com [Connection timed out #110]
stack trace
* at ()
in SF_ROOT_DIR/lib/vendor/symfony/lib/vendor/swiftmailer/classes/Swift/Transport/StreamBuffer.php line 235 ...
232. }
233. if (!$this->_stream = fsockopen($host, $this->_params['port'], $errno, $errstr, $timeout))
234. {
235. throw new Swift_TransportException(
236. 'Connection could not be established with host ' . $this->_params['host'] .
237. ' [' . $errstr . ' #' . $errno . ']'
238. );
* at Swift_Transport_StreamBuffer->_establishSocketConnection()
in SF_ROOT_DIR/lib/vendor/symfony/lib/vendor/swiftmailer/classes/Swift/Transport/StreamBuffer.php line 70 ...
67. break;
68. case self::TYPE_SOCKET:
69. default:
70. $this->_establishSocketConnection();
71. break;
72. }
73. }
* at Swift_Transport_StreamBuffer->initialize(array('protocol' => 'ssl', 'host' => 'smtp.gmail.com', 'port' => 465, 'timeout' => 30, 'blocking' => 1, 'type' => 1))
in SF_ROOT_DIR/lib/vendor/symfony/lib/vendor/swiftmailer/classes/Swift/Transport/AbstractSmtpTransport.php line 101 ...
98.
99. try
100. {
101. $this->_buffer->initialize($this->_getBufferParams());
102. }
103. catch (Swift_TransportException $e)
104. {
* at Swift_Transport_AbstractSmtpTransport->start()
in SF_ROOT_DIR/lib/vendor/symfony/lib/vendor/swiftmailer/classes/Swift/Mailer.php line 74 ...
71.
72. if (!$this->_transport->isStarted())
73. {
74. $this->_transport->start();
75. }
76.
77. return $this->_transport->send($message, $failedRecipients);
* at Swift_Mailer->send(object('Swift_Message'), array())
in SF_ROOT_DIR/lib/vendor/symfony/lib/mailer/sfMailer.class.php line 300 ...
297. return $this->realtimeTransport->send($message, $failedRecipients);
298. }
299.
300. return parent::send($message, $failedRecipients);
301. }
302.
303. /**
* at sfMailer->send(object('Swift_Message'))
in SF_ROOT_DIR/lib/vendor/symfony/lib/mailer/sfMailer.class.php line 263 ...
260. */
261. public function composeAndSend($from, $to, $subject, $body)
262. {
263. return $this->send($this->compose($from, $to, $subject, $body));
264. }
265.
266. /**
* at sfMailer->composeAndSend('tirengar#gmail.com', 'tirengarfio#hotmail.com', 'Confirm Registration', 'Hello fjklsdjf,<br/><br/> Click here to confirm your registration<br/><br/> Your login information can be found below:<br/><br/> Username: fjklsdjf<br/> Password: m')
in SF_ROOT_DIR/plugins/sfDoctrineGuardExtraPlugin/modules/sfGuardRegister/lib/BasesfGuardRegisterActions.class.php line 89 ...
86. $user->getEmailAddress(),
87. 'Confirm Registration',
88. $message
89. );
90. }
91.
92. /**
* at BasesfGuardRegisterActions->sendRegisterConfirmMail(object('sfGuardUser'), 'm')
in SF_ROOT_DIR/plugins/sfDoctrineGuardExtraPlugin/modules/sfGuardRegister/lib/BasesfGuard
This is my configuration in factories.yml.
all:
mailer:
param:
delivery_strategy: realtime
transport:
class: Swift_SmtpTransport
param:
host: smtp.gmail.com
port: 465
encryption: ssl
username: tirengarfio
password: XXXX
The port 465 is open the my remote host. No problem in localhost.
Any idea?
--
Javi
Ubuntu 8.04
I have taken these instructions directly from gmail site.
you have to use #gmail.com in your username.
Outgoing Mail (SMTP) Server - requires TLS: smtp.gmail.com (use authentication)
Use Authentication: Yes
Use STARTTLS: Yes (some clients call this SSL)
Port: 465 or 587
Account Name: your full email address (including #gmail.com)
Google Apps users, please enter username#your_domain.com
Password: your Gmail password
You need to open 465 on firewall
On CSF firewall you need to add 465 on TCP_OUT =
I don't know if this helps, buy I've run with the same problem on my local machine (Windows). For resolving this I had to copy two dlls on the php directory to system32(ssleay.dll and libeay.dll) and unncoment the extension php_openssl.dll on my apache configuration. There might be a similar solution for linux. I suggest you contact the hosting because it's quite possible that you cannot perform this solution on a shared hosting.
Well, I had the same problem for a while, replacing: smtp.gmail.com with 173.194.65.108 actually worked for me!
If you get this constantly without any luck, then check the settings again.
I was overlooking my settings and later found the host was wrong.
I used,
smtp.google.com
instead of
smtp.gmail.com
Too silly, but it happened to me.