Sunday, 16 October 2022

screenFetch - The Bash Screenshot Information Tool

I had been seeing this image everywhere but had no idea how to create it. Simple, a little application called Screenfetch is the answer to that question.
ScreenFetch is a system information tool that was created primarily for Bash Shell, while it can also work in other shell environments.
The programme will identify the Linux distribution you are using and create an ASCII version of the distribution's logo with some useful information to the right of the logo. The tool is very configurable; options include changing colours, disabling ASCII, and taking screenshots when information is shown.

Start by open a teminal Ctrl Alt T

Now you can install from the official repositories
apt install screenfetch

I also came across a comparable programme called neofetch while writing this, that is (in my experience) much faster.

apt install neofetch

I believe I'll stick with that one, but you should obviously make your own decision.
Saturday, 20 November 2021

Python convert hex to ascii

I've been having trouble with this simple task of converting a string of hexadecimal digits to text. My research and testing were insufficient. While the characters are not from extended ascii table, this is a easy task. But my strings can and will include letters like "áðéíóþæ". The sting comes from snmp and in this example I will be using the word "Ísland" for this demo hex "cd 73 6c 61 6e 64" Here is one of the most promising code snipped

 
import binascii

def hex_to_ascii(hex_str):
    hex_str = hex_str.replace(' ', '').replace('0x', '').replace('\t', '').replace('\n', '')
    ascii_str = binascii.unhexlify(hex_str)
    return ascii_str
 
hex_input = 'cd 73 6c 61 6e 64'
ascii_output = hex_to_ascii(hex_input)

print(format(ascii_output))

The output was b'\xcdsland' so it does not encode the first letter like all me previous tempts. Finally I found this snipped:
 
>>> L = [104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100]
>>> ''.join(chr(i) for i in L)
'hello, world'

Next step was to fit join(chr) in my snipped like so..
   
import binascii

def hex_to_ascii(hex_str):
    hex_str = hex_str.replace(' ', '').replace('0x', '').replace('\t', '').replace('\n', '')
    ascii_str = binascii.unhexlify(hex_str)
    return ascii_str
 
hex_input = 'cd 73 6c 61 6e 64'
ascii_output = hex_to_ascii(hex_input)
ascii_output = ''.join(chr(i) for i in ascii_output)

print(format(ascii_output))

--cheers
Wednesday, 10 November 2021

Command line upload to Dropbox

Dropbox OAuth Guide
It is sometimes useful to upload a file or files to Dropbox from the terminal or even by script. This snippet uploads a file to the directory's root.
 
curl -X POST https://content.dropboxapi.com/2/files/upload --header "Authorization: Bearer <Auth code> " --header "Dropbox-API-Arg: {\"path\": \"/filename.png\",\"mode\": \"add\",\"autorename\": true,\"mute\": false,\"strict_conflict\": false}" --header "Content-Type: application/octet-stream" --data-binary @filename.png
Monday, 8 November 2021

Convert an image and audio file to a video with ffmpeg

I needed a command line script to merge an image file with an audio file and generate a video file video.mp4 The first attempt was basic.
ffmpeg -loop 1 -i image.jpg -i audio.mp3 -c:a copy -c:v libx264 -shortest video.mp4
In most cases, this would do, but the image dimensions were not divisible by 2 resulting in an error.
[libx264 @ 0x56450842d500] height not divisible by 2 (640x427)
Error initializing output stream 0:0 -- Error while opening encoder for output stream #0:0 - maybe incorrect parameters such as bit_rate, rate, width or height
Conversion failed!
The current working version of the command line is as follows:
ffmpeg -loop 1 -i image.jpg -i audio.mp3 -vf "scale=2*trunc(iw/2):2*trunc(ih/2),setsar=1" -c:a copy -c:v libx264 -shortest video.mp4

Example:


Tuesday, 29 September 2020

How to disable the Caps Lock key on Ubuntu

Keyboard

I dont like Caps Lock, it's the the most unnecessary key on the keyboard in my opinion. I hardly ever write more than couple of words in capitals, but often accidently hit the key; suddenly finding myself TYPING IN ALL CAPS LIKE A SCREAMING MONKEY. Here’s an easy way to disable your Ubuntu’s Caps Lock key.

1. Install dconf

I already had this installed
$ sudo apt install dconf-tools

2. Disable caps lock (reenable by pressing both shift keys at once)

$ setxkbmap -option "caps:none"
$ setxkbmap -option "shift:both_capslock"
I did only disable for now.

-- UPDATE
This works but running this automatically is of course what was missing in this post so I added step 3 

3. Add this to your .bashrc file

vim .bashrc

Wednesday, 2 September 2020

Connecting to MS SQL server with pyodbc


Small project I'm working on at work requires connection to MS SQL server. For the task I'm using python3 with pyodbc library and I got stuck for a while trying to connect. looks like it has to do with the ODBC Driver 17 for SQL Server. After some time searching for solution, I found FreeTDS.

First install FreeTDS on your Linux:
apt install tdsodbc freetds-bin
Next configure FreeTDS by adding this to /etc/odbcinst.ini
[FreeTDS]
Description=FreeTDS
Driver=/usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so
Setup=/usr/lib/x86_64-linux-gnu/odbc/libtdsS.so
Finally activate
odbcinst -i -d -f /etc/odbcinst.ini
And now I can run pyodbc in my code
import pyodbc
connection = pyodbc.connect('DRIVER={FreeTDS};'
	'Server='+dbhost+';'
	'Database='+dbname+';'
	'UID='+dbuser+';'
	'PWD='+dbpass+';'
	'TDS_Version=8.0;'
	'Port=1433;')
    
cursor = connection.cursor()
cursor.execute("SELECT * FROM tablename; ")

for row in cursor:
	print(row)
Thursday, 23 April 2020

How to fix a "cURL error 28: Connection timed out" in WordPress?



My Wordpress Site Health Status check showed me some critical issues that I needed to take further look at. "The REST API request failed due to an error."

The REST API request failed due to an error

Error: cURL error 28: Operation timed out after 10000 milliseconds
 with 0 bytes received (http_request_failed)

After a lot of search results that did NOT lead me to the right direction I finally stumbled up on a short article about this subject. A few items in a list on "How to Fix" this. The most interesting line in the article mentioned the Query Monitor plugin to check the status of the HTTP API Calls in the admin page where the error is displayed. And that vas the single most helpful plugin I ever found. Within a minute I had identified the problem the problem which was I my case the WP Social Avatar plugin.

wp-social-avatar error

This Query Monitor plugin saved my day, but mostly a lot of time.

*** EDIT *** It turned out I had second plugin causing the same error. "PHP Code For Posts" that has has been closed and is no longer available for download.

--cheers
Monday, 7 October 2019

No default realm defined for Kerberos


When you connect to some old cisco routers using iterm2 on an OS X, it might takes some time before it prompts for a username. And it might also promt you with this message.
Kerberos: No default realm defined for Kerberos! 
To disable this message you need to create or edit the file .telnetrc in your home directory and add default unset autologin
$ vim ~/.telnetrc
  default unset autologin
esc : wq
Monday, 19 February 2018

WordPress Memory Exhausted Error


I've got allowed memory size exhausted error in WordPress. Well not for the first time and I guess it's not the last time.

Fatal error: Allowed memory size of 67108864 bytes exhausted (tried to allocate 12288 bytes) in /home/user/public_html/wp-admin/includes/menu.php on line 65

So the I increase PHP Memory Limit in WordPress in one easy step, by editing the wp-config.php file on the WordPress site. It is located in the WordPress site’s root folder, and you will need to use an FTP client or file manager in your web hosting control panel.

Add this line:

define( 'WP_MEMORY_LIMIT', '256M' );


before the line that says ‘That’s all, stop editing! Happy blogging.’

This tells WordPress to increase the PHP memory limit to 256MB And once you are done, you need to save your changes and upload your wp-config.php file back to your server, or save your file in the file managers editor.

Thursday, 15 February 2018

How to reprogramme the central locking on a Mazda 6



I ran into "key problem" with my car few days a go. The remote central locking stopped working and at first I put the blame on the battery in the key, so I changed the battery. That did not fix my problem and the remote central locking was still not working.
Now I really thought I was facing some expenses getting this fixed properly. But Internet to the rescue. After short search I found method that might be wort trying. Reprogramme the central locking.
Here are step by step instructions I found from The Car Key Man


1. Enter your car and leave the driver door open.
2. Turn the ignition key on and off three times (leave key in ignition)
3. Shut and open the door three times.
   a. You should hear the lock cycle.
4. Press one of the button two times on your key.
   a. You should hear the lock cycle.
   b. Take your second key, if you have one, and press twice.
      i. You should hear the lock cycle.
5. Turn the ignition on an off one time and take the key out.

The also have a demonstration video for this



--Cheers
Thursday, 12 October 2017

Telnet Removed in Mac OS High Sierra 10.13


Found out that telnet as been removed in Mac OS High Sierra 10.13 when I upgraded last night, which is bad for me as i work in networking and some legacy equipment still only has telnet. You can enable it with Homebrew. First, update or install Xcode from the App Store.

brew tap theeternalsw0rd/telnet
brew install telnet 

If Homebrew is not installed, it's available here >> brew.sh

Another option is to copy it from a backup, or other machine, if you have one into /usr/local/bin/

--cheers
Thursday, 19 January 2017

Change default Screenshot Save Location MacOS X


I take a lot of screenshots for different reasons. I keep some, post others on social media or I use them to illustrate my posts. The default save lcation is current users desktop, and you might find the desktop to be cluttered with the screenshot files rather quickly.

Keyboard Shortcuts to Capture a Screen Shot with Mac OS X

Save to location
⌘ Cmd + Shift + 3 - Entire screen
⌘ Cmd + Shift + 4 - Portion of the screen
⌘ Cmd + Shift + 4 then Space - Specific application window

Copy to clipbard
⌘ Cmd + Ctrl + Shift + 3 - whole screen capture
⌘ Cmd + Ctrl + Shift + 4 - selective capture
⌘ Cmd + Ctrl + Shift + 4 Space - window screen capture

How to change default Screenshot Save Location

Press ⌘ Cmd + Space to open Spotlight and type terminal or, as I prefer, iTerm 2
$ mkdir $HOME/Documents/Screenshots
$ defaults write com.apple.screencapture location $HOME/Documents/Screenshots/
$ killall SystemUIServer

You also might want to move all your existing screenshots from the desktop to your new folder.
$ mv $HOME/Desktop/Screen\ Shot\ *.png $HOME/Documents/Screenshots/.

Change the default screenshot file name

The default screenshot name is "Screen Shot 2017-01-18 at 10.56.49.png"
[Name] [date] at [time].[type] You can only change the [Name] and [type]

$ defaults write com.apple.screencapture name "Prefix Name"

Change the screenshot image type

By default, OS X saves screenshots as .png (or Portable Network Graphics) files. Valid formats: .bmp, .pdf, .jpg, .jp2, .tif, .pict, .tga and .png

$ defaults write com.apple.screencapture type jpg
Tuesday, 3 January 2017

Mac OSX keeps prompting for SSH key passphrase


So, since I upgraded my MAC to OSX 10.12.2 I always get promted for my SSH key passphrase witch is rather annoying.
$ ssh example.com
Enter passphrase for key '/Users/<username>/.ssh/id_rsa':
This passphrase was stored in Keychain and was unlocked when I unlock my MAC
By adding UseKeychain yes to your ~/.ssh/config it solves this problem.
$ cat ~/.ssh/config
Host *
  UseKeychain yes
In courtesy of  @aral on Twitter.
You can also read more about Keychain changes in Technical Note TN2449
Keychain changes
Prior to macOS Sierra, ssh would present a dialog asking for your passphrase and would offer the option to store it into the keychain. This UI was deprecated some time ago and has been removed.
Instead, a new UseKeychain option was introduced in macOS Sierra allowing users to specify whether they would like for the passphrase to be stored in the keychain. This option was enabled by default on macOS Sierra, which caused all passphrases to be stored in the keychain
--Cheers
Sunday, 18 December 2016

Run a TFTP Server on Mac OS X



To upgrade firmware or upload config backup on networking devices TFTP server often comes handy. In my job I usually have access tosuch server, but in some cases when network access is limited or not available I configure a TFTP server on my laptop. For Linux see: Install and run a TFTP server

Mac OS X has a tftp server included, it's eazy to start it and do a minor configuration. First see if there are any commands related to tftp.
apropos tftp
You should get answer like this.
tftp(1) - trivial file transfer program
tftpd(8) - DARPA Internet Trivial File Transfer Pro
You can start it with launchctl
sudo launchctl load -F /System/Library/LaunchDaemons/tftp.plist
To confirm it’s running use netstat to check what is listening on its port, traditionally port 69.
netstat -na |grep \*.69
Should get answer like this.
udp6       0      0  *.69                   *.*
udp4       0      0  *.69                   *.*
It's a good idea to symlink the tftpboot to a folder you have full control over because OS X El Capitan has strong security via its System Integrity Protection (SIP) which makes things more difficult.
cd /private/
sudo rm -rf tftpboot
mkdir /Users/<username>/tftpboot
sudo ln -s /Users/<username>/tftpboot tftpboot
sudo launchctl unload -F /System/Library/LaunchDaemons/tftp.plist
sudo launchctl load -F /System/Library/LaunchDaemons/tftp.plist

When you’re not using the TFTP server, make sure to unload the service.
sudo launchctl unload -F /System/Library/LaunchDaemons/tftp.plist
netstat -na |grep \*.69
The netstat should return nothing.

-cheers
Wednesday, 5 October 2016

Restoring a single table from a full mysqldump file



Yesterday I needed to restore one table from larger database dump file. To begin with I found out which lines I needed end with sed i got my data.
sed -n 955,991p data.sql > new_data.sql
Pretty easy, but in a large file you have to work your way to find the line you need. The solution I found was more specific and works like a charm. The first version of the command was a rather inaccurate because it was missing the "DROP TABLE IF EXIST" for the table you are restoring and you need to edit out few lines from the bottom of the new file before using it in order to prevent deleting the next table, "address". leaves "DROP TABLE IF EXIST" for the next table at the end of the new file.
sed -n -e '/CREATE TABLE.*`person`/,/CREATE TABLE/p' data.sql > new_data.sql
Leves this at the end og the new file.
--
-- Table structure for table `address`
--

DROP TABLE IF EXISTS `address`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `address` (

Then I came a cross better solution to get your table data. While this is the backup layout.
--
-- Table structure for table `person`
--

DROP TABLE IF EXISTS `person `;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `person` (
  `id` int(4) NOT NULL AUTO_INCREMENT,
  `name` varchar(225) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `person`
--

LOCK TABLES `person` WRITE;
/*!40000 ALTER TABLE `person` DISABLE KEYS */;
INSERT INTO `person` VALUES (1,'Emma'),(2,'Noah'),(3,'Olivia'),(4,'Liam'),(5,'Sophia');
/*!40000 ALTER TABLE `person` ENABLE KEYS */;
UNLOCK TABLES;

As you can see "UNLOCK TABLES" is the last line, so that is what we look for in the sed ccommand.
sed -n -e '/DROP TABLE IF EXISTS.*`person`/,/UNLOCK TABLES/p' data.sql > new_data.sql

Now your new file should be ready to use, but I recommend that you check before you use.

--cheers
Monday, 12 September 2016

How to disable the Caps Lock key on Mac


Caps Lock is the the most unnecessary key on the keyboard for me. I rarely need to write more than couple of words in capitals and to often I accidently hit the key, suddenly finding myself typing IN ALL CAPS
Here’s an easy way to change the behavior of your Mac’s Caps Lock key and even disable it altogether.

  • Click the  icon in the top-left corner of your desktop and select System Preferences
  • Select the Keyboard icon and click the “Modifier Keys” button in the bottom-right corner 
  • From the pull-down menu next to “Caps Lock Key”, select “No Action” 
  • Press “OK”



Monday, 20 June 2016

How you can make someone unfollow you on Twitter

This trick is known as a "soft block", and it comes handy when someone’s annoying you on Twitter and you really do not want to block him. You have a few options for dealing with annoying accounts.
Block, which prevents them seeing your tweets.
Mute, which stops you seeing their tweets and replies to you.
And Soft block which forces them to unfollow you.
If you are active Twitter user you are most likely familiar to Block and Mute. But you might or might not have heard about Soft block. Because It’s not an official feature, soft block is not commonly known.
The procedure is quite simple, all you have to do is promptly block and unblock the user in question.

If the person doesn’t notice you’re not coming up in their feed anymore, you’re good. Else repeat.

--Cheers


Wednesday, 25 May 2016

Restoring applications after minimizing to Mac OS X dock


When you click the yellow pill button in the upper left corner of a window to minimize that window in Mac OS X or if you use ⌘ Cmd + M you might want to bring the application back. When cycling through running applications, including the minimised applications, using ⌘ Cmd + Tab you might expect to retrieve the application back.

This sequence on the other hand will bring wour application window.
1. Use ⌘ Cmd + Tab untill you find your application.
2. Before releasing ⌘ Cmd, press and hold ⌥ Alt

Other method is to hide application using ⌘ Cmd + H, then you can restore your window with ⌘ Cmd + Tab
Thursday, 12 May 2016

Using Python, MySQL and UTF-8

I have been spending way to long time figuring out how I can encode my data to utf8 when fetching records from MySQL database. All the time I was focusing on encoding the output, resulting in error like this one.
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe1 in position 1: 
ordinal not in range(128)
The solution I finally found is to set the character set when I prepare the MySQL connection
con.set_character_set('utf8')
Ending up in my code like this.
!/usr/bin/env python
# -*- coding: utf-8 -*-
import MySQLdb as mdb

def getname(p):
    con = mdb.connect('hostname', 'username', ' password', 'databasname')
    con.set_character_set('utf8')
    sql = "SELECT cellname1 from tablename where cellname2='%s'"%(str(p))
    cur = con.cursor()
    cur.execute(sql)
    row = cur.fetchone()
    if not row:
        return 'n/a'
    else:
        return str(row[0])
    cur.close()
Now everything works like a charm.
Tuesday, 15 December 2015

How To Allow Usb To Serial Adapters In Osx “el Capitan


In my line of work I use serial port on some devices frequently and most new computers do not have serialport. In Linux I found out that it’s easy to connect using usb to serial and screen, but now when I’ve got mac it looks like there is no driver for the usb to serial by default.
I bought PL-2303 Driver (€6.17/$7.36) and all my problems are solved. It'a easy and fast installation.
After I connect the USB serial converter I simply type in:
screen /dev/tty.Repleo-PL2303-00001014
-cheers