Gammu on raspberry Zero - raspberry-pi

I am trying to setup a raspberry zero to collect the temperature from a DS18B20 probe connected to a -20°C fridge of my lab. If a temperature above a certain value is detected, the raspberry should send an email to alert for a a problem. I use a chinese (IEASUN Technology) HSUPA modem with a Qualcom chip. Gammu is used to communicate with the modem. After installing gammu and my script, everything worked as expected. Then, I decided to add a function: upon sending a sms to the raspberry, I wanted that it sent back the temperatures of the connected probes (and I had to install gammu-smsd). This new function is working but my original alert script does not work anymore.
I must emphasise that this is done as an autodidact with minimal knowledge in coding (this will be obvious in the code).
Here are several key information.
When I run my 'Alert' script, now, I have this message:
Traceback (most recent call last):
File "sendsmstemp.py", line 11, in <module>
sm.Init()
gammu.ERR_DEVICEOPENERROR: {'Text': u'Error opening device. Unknown, busy or no permissions.', 'Code': 2, 'Where': 'Init'}
The code of my 'Alert' script is:
import gammu
import sys
# Create state machine object
sm = gammu.StateMachine()
# Read ~/.gammurc
sm.ReadConfig()
# Connect to phone
sm.Init()
import time
while 1:
        tempfile1 = open("/sys/bus/w1/devices/28-031689cf76ff/w1_slave")
        thetext1 = tempfile1.read()
        tempfile1.close()
        tempdata1 = thetext1.split("\n")[1].split(" ")[9]
        temperature1 = float(tempdata1[2:])
        temperature1 = temperature1 / 1000
if temperature1>-10:
     
message1 = {
'Text': 'Time is:' + time.strftime('%H:%M:%S')+'| Temperature Fridge 1 above -10°C!! . If still above the limit, another sms will be sent in 30min',
'SMSC': {'Location': 1},
'Number': '+Myphonenumber',
'Validity': 'Max',
}
sm.SendSMS(message)
#It waits 30min before sending another sms
time.sleep(1800)
Else:
#test the probe every min
time.sleep(60)
This code is launched at startup with this sh script:
#!/bin/sh
sleep 10
sudo python /home/pi/smstemp/sendsmstemp.py
The last script that I have added to this raspberry — which required the installation of gammu-smsd package — that has apparently broken the first one is:
#!/bin/sh
from=$SMS_1_NUMBER
message=$SMS_1_TEXT
#ThisHost=$(hostname)
# local file to write into
#FILE=$ThisHost"-status.txt"
# local directory to write to file and pick it for upload
#REPERTOIRE="/home/pi/sendsmstemp/"
#echo $REPERTOIRE$FILE
#Read last temperature 
temperature1=$(find /sys/bus/w1/devices/ -name "28-*6ff" -exec cat {}/w1_slave \; | grep "t=" | awk -F "t=" '{print $2/1000}')
#Send message
reply=""
echo "Temp Fridge 1: $temperature1" | sudo gammu sendsms TEXT "$from"
Now, my /etc/gammu-smsdrc config file looks like that:
[gammu]
device = /dev/ttyUSB0
name = Phone on USB serial port Qualcomm__Incorporated Qualcomm_CDMA_Technologies_MSM
connection = at
gammucoding = utf8
[gammu1]
device = /dev/ttyUSB1
name = Phone on USB serial port Qualcomm__Incorporated Qualcomm_CDMA_Technologies_MSM
connection = at
gammucoding = utf8
[gammu2]
device = /dev/ttyUSB2
name = Phone on USB serial port Qualcomm__Incorporated Qualcomm_CDMA_Technologies_MSM
connection = at
gammucoding = utf8
[gammu3]
device = /dev/ttyUSB3
name = Phone on USB serial port Qualcomm__Incorporated Qualcomm_CDMA_Technologies_MSM
connection = at
gammucoding = utf8
[smsd]
service = files
#logfile = syslog
logfile = /var/spool/gammu/log/gammu-smsdrc.log
# Change PIN code
pin = 1234
RunOnReceive = /home/pi/sendsmstemp/sendinfo.sh
My /etc/gammurc config file is the same (except that the last line is not included).
The gamma-detect command returns that:
[gammu]
device = /dev/ttyUSB0
name = Phone on USB serial port Qualcomm__Incorporated Qualcomm_CDMA_Technologies_MSM
connection = at
[gammu1]
device = /dev/ttyUSB1
name = Phone on USB serial port Qualcomm__Incorporated Qualcomm_CDMA_Technologies_MSM
connection = at
[gammu2]
device = /dev/ttyUSB2
name = Phone on USB serial port Qualcomm__Incorporated Qualcomm_CDMA_Technologies_MSM
connection = at
[gammu3]
device = /dev/ttyUSB3
name = Phone on USB serial port Qualcomm__Incorporated Qualcomm_CDMA_Technologies_MSM
connection = at
The gammu --identify returns that:
Device : /dev/ttyUSB1
Manufacturer : Qualcomm
Model : unknown (+CGMM:HSPA MODEM)
Firmware : +CGMR:V1.1
IMEI : 356793034431627
SIM IMSI : +CIMI:208150010138412
The gammu getsecuritystatus returns that:
Nothing to enter.
And using this command works as expected (it send a sms):
gammu sendsms TEXT 06xxxxxxxx -text "Test"
Why my 'Alert' script is not running??? I am lost.
Many many thanks for your help!!

As explained in my comment to my question, I gave up. I have amended and debugged the alert script, for those that might be interested (it works with 2 probes and it is easy to add other probes):
#!/usr/bin/env python
# encoding: utf-8
import gammu
import sys
# Create state machine object
sm = gammu.StateMachine()
# Read ~/.gammurc
sm.ReadConfig()
# Connect to phone
sm.Init()
import time
while 1:
    tempfile1 = open('/sys/bus/w1/devices/28-031689cf76ff/w1_slave')
    tempfile2 = open('/sys/bus/w1/devices/28-051691e603ff/w1_slave')
    thetext1 = tempfile1.read()
    thetext2 = tempfile2.read()
    tempfile1.close()
    tempfile2.close()
    tempdata1 = thetext1.split("\n")[1].split(" ")[9]
    tempdata2 = thetext2.split("\n")[1].split(" ")[9]
    temperature1 = float(tempdata1[2:])
    temperature2 = float(tempdata2[2:])
    temperature1 = temperature1 / 1000
    temperature2 = temperature2 / 1000
    if int(temperature1) > -10 or int(temperature2) > -10:
        #Tony
        message = {
        'Text': time.strftime('%H:%M') + '\r\nTemperature of a Team 1 Fridge above -10deg' + '\r\nFridge 1=' + str(temperature1) + 'deg\r\nFridge 2=' + str(temperature2) + 'deg\r\nIf still above the limit, another SMS will be sent in 30 min',
        'SMSC': {'Location': 1},
        'Number': '+336XXXXXXXXX',
        'Validity': 'Max',
        }
        sm.SendSMS(message)
        time.sleep(1800)
        #Check every min
        time.sleep(60)

Related

packer error Failed to send shutdown command: dial tcp 172.29.48.100:22: i/o timeout

I am trying packer builder with provisioner "shell-local". After successful OS installation I am trying to attach second network adapter. But it stuck in this error. Platform Hyper-V. Code looks like:
source "hyperv-iso" "build-debian" {
boot_command = ["<wait><wait><wait><esc><wait><wait><wait>",
"/install.amd/vmlinuz ",
"initrd=/install.amd/initrd.gz ", "auto=true ", "interface=eth0 ",
"netcfg/disable_dhcp=true ",
"netcfg/confirm_static=true ", "netcfg/get_ipaddress=172.29.48.100 ",
"netcfg/get_netmask=255.255.255.0 ",
"netcfg/get_gateway=172.29.48.1 ", "netcfg/get_nameservers=8.8.8.8 8.8.4.4 ",
"netcfg/get_domain=domain ",
"netcfg/get_hostname=hostname ", "url=http://{{ .HTTPIP }}:{{ .HTTPPort }}/preseed.cfg ",
"vga=788 noprompt quiet --<enter> "]
boot_wait = "10s"
configuration_version = "${var.hyperv_version}"
cpus = "${var.cpus}"
disk_block_size = "${var.hyperv_disk_block_size}"
disk_size = "${var.disk_size}"
memory = "${var.memory}"
generation = "${var.hyperv_generation}"
guest_additions_mode = "disable"
http_directory = "${local.http_directory}"
iso_checksum = "sha256:e307d0e583b4a8f7e5b436f8413d4707dd4242b70aea61eb08591dc0378522f3"
iso_url = "http://debian.mirror.vu.lt/debian-cd/11.5.0/amd64/iso-cd/debian-11.5.0-amd64-netinst.iso"
output_directory = "${var.build_directory}/packer-${local.template}-${var.git_sha}"
shutdown_command = "echo 'vagrant' | sudo -S /sbin/halt -h -p"
ssh_host = "${var.ip_address_eth0}"
ssh_keep_alive_interval = "-1s"
ssh_password = "vagrant"
ssh_port = 22
ssh_timeout = "120m"
ssh_username = "vagrant"
headless = "false"
switch_name = "VmNAT"
vm_name = "${local.template}-${var.git_sha}"
}
build {
name = "BUILD: Debian v11.5"
source "hyperv-iso.build-debian" {
}
provisioner "shell-local" {
execute_command = ["powershell.exe", "{{.Vars}} {{.Script}}"]
env_var_format = "$env:%s=\"%s\"; "
tempfile_extension = ".ps1"
pause_before = "60s"
inline =["Import-Module Hyper-V",
"Stop-VM -Name ${local.template}-${var.git_sha}",
"Timeout /T 20",
"Add-VMNetworkAdapter -VMName ${local.template}-${var.git_sha} -SwitchName ${var.hyperv_switch} -Name Static -DeviceNaming Off",
"Start-VM -Name ${local.template}-${var.git_sha}"
}
}
packer logs
Maybe I'm doing something wrong? And someone know how to fix ? Ty for any help
EDITED:
I made some changes and I think its problem with timeout. While provisioned VM are restarted packer after that tries reconnect to VM, but in this time VM still booting and I get errors like. Is that possible that ssh_timeout works only on first boot ?

How do I error handling in Invoke-WebRequest?

2022-12-01: проблема ЧАСТИЧНО решена к версии 7.3.
The documentation recommends «Try-Catch». The problems are as follows.
0. Update: https://github.com/PowerShell/PowerShell/issues/16145
The «Catch [System.Net.WebException]» option has never worked for me, «Catch [System.Management.Automation.RuntimeException]» has always been activated. It is activated when divided by zero, for example. Can they be separated into different groups?
For different errors, the method and property sets of the automatic variable «$_ » in the «Catch»-block are different. Accessing the method BEFORE ERROR UNDERSTANDING may cause a new error. So far, I see ONLY ONE constant parameter: «$_.Exception.HResult». Is it really the ONLY one? There is not a word in the documentation about this.
At the break of the connection during the downloading process (for example, the router rebooted) no error occurs at all, the next statement in the «Try»-block is executed and «$Error.Count» is not increased, and the file on the disk remains PARTIALLY downloaded (although with some types of content it may be absent, it seems). Is it normal?
The third-party utility «cURL» at break of connection return errors with NON-ZERO codes 18 and 28 (perhaps, and others, I don't remember for sure). In PowerShell is this possible?
Notabene: to reboot the router or disconnect the cable you must to use your hands, not sample of my code.
Removed.
The part of my program written in the language that I know (not English).
$Error.Count
Try {
    # Для самых НЕвнимательных ПОВТОРЯЮ И ПОДЧЁРКИВАЮ, что
    # меня интересуют ошибки «Invoke-WebRequest»,
    # а НЕ ДЕЛЕНИЯ. Как их отделить друг от друга?
    # Именно об этом я написал в исходном вопросе!
    <# 1/0 # Для проверки этого случая раскомментируйте вручную. #>
    Invoke-WebRequest -URI СсылкаНаБольшойФайл -ErrorAction Stop
    $Error.Count
} Catch [System.Net.WebException] { # In THIS order!
    "Эта секция не выполняется НИКОГДА."
} Catch [System.Management.Automation.RuntimeException] {
    "Эта секция выполняется ВСЕГДА при ошибках 1/0 and «IWR»."
    "Управление попадает сюда при ЛЮБЫХ ошибках из моего примера,"
    " КАК арифметических, ТАК и сетевых. Всё в одну кучу."
    # Для самых НЕвнимательных ПОВТОРЯЮ И ПОДЧЁРКИВАЮ, что
    # меня интересуют ошибки «Invoke-WebRequest»,
    # а НЕ ДЕЛЕНИЯ. Как их отделить друг от друга?
    # Именно об этом я написал в исходном вопросе!
    # Следующая строка может вызвать ошибку,
    # потому что такого метода/свойства просто нет.
    # А может выполниться БЕЗ прерывания. Как повезёт.
    $_.Exception.InnerException.ErrorCode
    "В документации НИ слова о том,"
    " какие элементы (методы/свойства) присутствуют ВСЕГДА."
} Catch [System.SystemException] { # In THIS order!
    "Эта секция не выполняется НИКОГДА."
} Catch { # In THIS order!
    "Эта секция не выполняется НИКОГДА."
}
So I've run your code and have observed the following:
PowerShell 5.1 emits a WebException on failure.
PowerShell 7 emits a System.Net.Http.HttpRequestException, if you catch that it would separate the web exceptions from your hypothetical divide by zero.
If the inner exceptions of your HttpRequestException is a SocketException then you can use the ErrorCode field to get the underlying Windows Sockets error:
try{
$res = Invoke-WebRequest -URI 'https://notexist.example.com/' -ErrorAction Stop
}catch[System.Net.Http.HttpRequestException]{
$_.exception.innerexception.errorcode
}
11001
A list of the possible codes is here: https://learn.microsoft.com/en-us/windows/win32/winsock/windows-sockets-error-codes-2
However at this point you've got to ask yourself are you really going to take a different action in your code for a DNS failure, a connection failure, connection refused, and every other possible option on that list?
As for your final point, when I unplug the network cable PowerShell 7 just hangs indefinitely, that could be this open bug: https://github.com/PowerShell/PowerShell/issues/12249

Problem with tac_plus.cfg on Tacacs GUI with error ' /opt/tacacsgui/tac_plus.cfg_test:47: Unrecognized keyword 'host''

I got error when try to apply my tacacs gui configuration, i try this configuration with different server on localhost and it's working but not on my first server tacacs
/opt/tacacsgui/tac_plus.cfg_test:47: Unrecognized keyword 'host'
Please help me fix this issue, this my tac_plus.cfg :
id = spawnd {
####SPAWND####
listen = { port = 49 }
} ##END OF SPAWND
id = tac_plus { ##START GLOBAL CONFIGURATION
####GENERAL CONFIGURATION####
###MANUAL CONFIGURATION START###
log = accounting_log {
destination = "| /opt/tacacsgui/parser/tacacs_parser.sh accounting"
log separator = "|!|"}
log = authentication_log {
destination = "| /opt/tacacsgui/parser/tacacs_parser.sh authentication"
log separator = "|!|"}
log = authorization_log {
destination = "| /opt/tacacsgui/parser/tacacs_parser.sh authorization"
log separator = "|!|"}
###MANUAL CONFIGURATION END###
accounting log = accounting_log
authentication log = authentication_log
authorization log = authorization_log
connection timeout = 600
context timeout = 3600
password max-attempts = 1
password backoff = 1
separation tag = "*"
skip conflicting groups = yes
skip missing groups = yes
####MAVIS GENERAL SETTINGS####
user backend = mavis
login backend = mavis chpass
pap backend = mavis
mavis module = external {
exec = /opt/tacacsgui/mavis/app.php
} #END OF MAVIS GLOBAL SETTINGS
####LIST OF ACL####
####LIST OF DEVICE GROUPS####
host = defaultGroup {
welcome banner = "Unauthorized access is prohibited!"
motd banner = "Today is a perfect day! Have a nice day!"
failed authentication banner = "Go away! Unauthorized access is prohibited!"
} #END OF defaultGroup
host = datacomm {
key = "telkomcel"
enable = clear telkomcel
default group = datacomm_full
} #END OF datacomm
host = servicesolution {
key = "telkomcel"
enable = clear telkomcel
} #END OF servicesolution
####LIST OF HOSTS####
host = SW-CORE2 {
address = "192.168.101.12/32"
key = "telkomcel"
enable = clear telkomcel
template = datacomm
} #END OF SW-CORE2
host = PE2-INET-AIM {
address = "192.168.101.10/32"
key = "telkomcel"
enable = clear telkomcel
template = servicesolution
} #END OF PE2-INET-AIM
host = SRDLI02 {
address = "192.168.101.14/32"
key = "telkomcel"
enable = clear telkomcel
template = datacomm
} #END OF SRDLI02
####LIST OF USER GROUPS####
group = datacomm_full {
#### LDAP Groups List #### DistinguishedName ###
### CN=Users,CN=Builtin,DC=telkomcel,DC=tl ###
enable = clear telkomcel
default service = permit
###Service full START###
service = shell {
set priv-lvl = 15
default attribute = permit
default cmd = permit
} #END OF Cisco Router/Switch Service
###Service full END###
} #END OF datacomm_full
group = servicesolution_full {
#### LDAP Groups List #### DistinguishedName ###
### CN=Users,CN=Builtin,DC=telkomcel,DC=tl ###
enable = clear telkomcel
server = deny SW-CORE2
server = deny SRDLI02
default service = permit
###Service full START###
service = shell {
set priv-lvl = 15
default attribute = permit
default cmd = permit
} #END OF Cisco Router/Switch Service
###Service full END###
} #END OF servicesolution_full
group = servicesolution_read {
#### LDAP Groups List #### DistinguishedName ###
### CN=Users,CN=Builtin,DC=telkomcel,DC=tl ###
enable = clear telkomcel
server = deny SW-CORE2
server = deny SRDLI02
default service = permit
###Service read_only START###
service = shell {
set priv-lvl = 3
default attribute = permit
default cmd = permit
} #END OF Cisco Router/Switch Service
###Service read_only END###
} #END OF servicesolution_read
group = datacomm_read {
#### LDAP Groups List #### DistinguishedName ###
### CN=Users,CN=Builtin,DC=telkomcel,DC=tl ###
enable = clear telkomcel
default service = permit
###Service read_only START###
service = shell {
set priv-lvl = 3
default attribute = permit
default cmd = permit
} #END OF Cisco Router/Switch Service
###Service read_only END###
} #END OF datacomm_read
####LIST OF USERS####
user = 91007 {
login = mavis # LDAP
member = datacomm_read
pap = login # Clone login
enable = login # Clone login
default service = permit
###Service full START###
service = shell {
set priv-lvl = 15
default attribute = permit
default cmd = permit
} #END OF Cisco Router/Switch Service
###Service full END###
} #END OF 91007
user = 88014 {
login = mavis # LDAP
member = datacomm_read
pap = login # Clone login
enable = login # Clone login
default service = permit
###Service read_only START###
service = shell {
set priv-lvl = 3
default attribute = permit
default cmd = permit
} #END OF Cisco Router/Switch Service
###Service read_only END###
} #END OF 88014
user = 82001 {
login = mavis # LDAP
member = servicesolution_full
pap = login # Clone login
enable = login # Clone login
default service = permit
### GET SERVICES FROM GROUP
} #END OF 82001
user = 94003 {
login = mavis # LDAP
member = servicesolution_full
pap = login # Clone login
enable = login # Clone login
default service = permit
### GET SERVICES FROM GROUP
} #END OF 94003
user = 89014 {
login = mavis # LDAP
member = datacomm_full
pap = login # Clone login
enable = login # Clone login
default service = permit
### GET SERVICES FROM GROUP
} #END OF 89014
user = 18001 {
login = mavis # LDAP
member = servicesolution_read
pap = login # Clone login
enable = login # Clone login
default service = permit
### GET SERVICES FROM GROUP
} #END OF 18001
}##END GLOBAL CONFIGURATION
please help how can i solve this issue without re-installing tacacs server
I have faced the same issue earlier. This is because of the special character in Name. I replace the special character form name and it's working for me.

How to get public IP of azure VM from the below terraform code

I have a terraform code which needs to retrieve public ip of a vm, here is my code
# Create virtual machine
resource "azurerm_virtual_machine" "myterraformvm" {
name = "myTerraformVM"
location = "Central India"
resource_group_name = "rg-mpg-devops-poc"
network_interface_ids = ["/subscriptions/*************/resourceGroups/rg-mpg-devops-poc/providers/Microsoft.Network/networkInterfaces/nic-mpg-devops"]
vm_size = "Standard_DS1_v2"
storage_os_disk {
name = "myOsDisk"
caching = "ReadWrite"
create_option = "FromImage"
managed_disk_type = "Premium_LRS"
}
os_profile {
computer_name = "myvm"
admin_username = "azureuser"
}
os_profile_linux_config {
disable_password_authentication = true
ssh_keys {
path = "/home/azureuser/.ssh/authorized_keys"
key_data = "ssh-rsa *********************"
}}
boot_diagnostics {
enabled = "true"
storage_uri = "https://*******.blob.core.windows.net/"
}}
Here am using NIC id , which will provide public ip by default, Can some one help me on this?
you would use data module for that:
data "azurerm_network_interface" "test" {
name = "acctest-nic"
resource_group_name = "networking"
}
that will give you NIC object, that will have ip_configuration block, that (in turn) will have public_ip_address_id parameter and you will use that to get data for the public ip:
data "azurerm_public_ip" "test" {
name = "name_of_public_ip"
resource_group_name = "name_of_resource_group"
}
output "domain_name_label" {
value = "${data.azurerm_public_ip.test.domain_name_label}"
}
output "public_ip_address" {
value = "${data.azurerm_public_ip.test.ip_address}"
}
you will have to parse resource ID into resource group\name of the resource obviously, but that can be easily done with split + array index
https://www.terraform.io/docs/providers/azurerm/d/public_ip.html
https://www.terraform.io/docs/providers/azurerm/d/network_interface.html
I tried this and could not retrieve the public IP. (more than likely pilot error.)
In my case I needed to retrieve an address for installing chef in a later step, so IP or FQDN would work. Here is how I got through this:
When creating my public ip, I added the domain label. Use this same value when you define your machine name.
resource "azurerm_public_ip" "CSpublicip" {
name = "myPublicIP"
location = "eastus"
resource_group_name = "${azurerm_resource_group.CSgroup.name}"
allocation_method = "Dynamic"
domain_name_label = "csvm${random_integer.server.result}"
When you add the domain label, Azure creates a reachable FQDN. Once you have that, you can use/retrieve the fqdn.
output "AzurePage" {
value = "${azurerm_public_ip.CSpublicip.fqdn}"

How to send mail with attachment on Amazon SES Service

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed yesterday.
Improve this question
Hi I am not able to send mail with attachement
My code :
$sendername ='Admin';
$senderemail ='kraj#seasiaconsulting.com';
$recipentemail = 'kraj#seasiaconsulting.com';
$se = new Zend_Service_Amazon_Ses_Email();
$mail = new Zend_Service_Amazon_Ses_Email();
$mail->setBodyHtml($message);
$mail->setFrom($senderemail,$sendername);
$mail->addTo($recipentemail,$recipentname);
$mail->addCc($senderemail,$sendername);
$mail->setReturnPath($senderemail);
$mail->setSubject($subject);
//attachments code
if($filesPathArray){
//$at = new Zend_Mime_Part($filesPathArray["pdf"]);
$at = new Zend_Mime_Part($filesPathArray["pdf"]);
$at->type = 'pdf';
//$at->filename = basename($filesPathArray["pdf"]);
$at->filename = $filesPathArray["pdf_name"];
$at->disposition = Zend_Mime::DISPOSITION_INLINE;
$at->encoding = Zend_Mime::ENCODING_BASE64;
$mail->addAttachment($at);
}
$ses = new Zend_Service_Amazon_Ses();
$messageId = $ses->sendEmail($mail);