Showing posts with label Linux. Show all posts
Showing posts with label Linux. Show all posts
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.
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:


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)
Friday, 21 February 2014

Installing LAMP (Linux, Apache, MySQL and PHP) On Linux

I'm running XLinux on my laptop and need to install webserver with php and MySQL, LAMP. (Linux, Apache, MySQL, PHP). Really thats a simple task, and I'm going do demostrate how

Step one, Install Apache

Open your terminal CTRL+ALT+T and enter following line.
sudo apt-get install apache2
Test Apache using this address in browser http://localhost/ and you will see a message saying:
It works!
This is the default web page for this server.
The web server software is running but no content has been added, yet.

Step two, install PHP

sudo apt-get install php5 libapache2-mod-php5
Restart Apache
sudo /etc/init.d/apache2 restart
Now we can test php by adding to the terminal
sudo gedit /var/www/test.php
This will open up a file called test.php
Add following line
<?php
phpinfo();
?>
Open http://localhost/test.php in browser, you should see info about your php

Step three, install MySQL

Open the Terminal and then copy/paste or type this line
sudo apt-get install mysql-server
And it's done. You can now access your MySQL server like this
mysql -u root -p
--cheers
Friday, 7 February 2014

How to create animated gif from video or images

There are many websites that generate animated gif from video for you, but most of them leave a watermark or logo on the gif. You can easily create your own and in this example we are going to use OpenShot 1.4.3 and command line tool, convert
First step is to select a video and edit it in OpenShot, select the part you like to animate and cut out everything else. If you already have sequince of images to use go strait to second step.
I selected very simple video only containing spinning dots.


To add files you can use CTRL+F and browse for file from there, or click on the "plus" sign. Next you drag the imported file down to the track part of OpenShot where you ca examine and cut the video. I selected ~2 sec to use of my video. Next you need to export the video, CTRL+E or the red circle. Now you can select where too and how. First select destination, I prefer to use new/empty directory.

Remember to set filename with leading zero; filename_%02d

Export 2
Export to "image sequence. Image format.
Now you might have some number of images.
Second step.
You should browse the images to see if the fit the loop you are aiming for. In my example I deleted first few and last few, leaving about 29 images.
The gif can get quite big, in that case see if you need to scale the images. My images are 720x480 px, and I like to scale the down to 45% of that size.


for file in *.png; do convert $file -resize 45% c-$file; done
Third step. After scaling the images it's time to create animated gif.
convert -delay 4 -loop 0 *.png my_animation.gif

Here is the final image.

Wednesday, 15 January 2014

SSH with DSA public key authentication - password less login

After taking pictures on your raspberry pi you might want to transfer the images to your PC. You can use several methods but I'm going to use scp over ssh using password less login. That way I can automate the transfer.
In this example I used following devices

Raspberry pi, IP 192.168.1.10 and user pi
Linux laptop, IP 192.168.1.20 and user foo

Step 1: Create Authentication SSH-Kegen Keys on the raspberry pi

Login to your rpi 192.168.1.10 with user pi to generate a pair of public keys
[pi@raspbmc ~]$ ssh-keygen -t dsa
If you do not want to give your file a name, just press enter. Or you can
Generating public/private dsa key pair.
Enter file in which to save the key (/home/pi/.ssh/id_dsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in .ssh/id_dsa.
Your public key has been saved in .ssh/id_dsa.pub.
The key fingerprint is:
83:8d:95:48:d3:25:11:48:f5:de:53:47:98:54:a2:b6 pi@pi
The key's randomart image is:
+--[ DSA 1024]----+
|         .++==++o|
|         ..+.+o..|
|          +   o.o|
|       o o   . +o|
|      . B   . .Eo|
|         .   .  .|
|            . +  |
|    a   o.       |
|          .      |
+-----------------+

Step 2: Upload Generated Public Keys to – 192.168.1.20

Use SSH from server 192.168.1.1 and upload new generated public key (id_rsa.pub) on server 192.168.1.20 under pi‘s .ssh directory as a file name authorized_keys.
[pi@raspbmc ~]$ cat .ssh/id_rsa.pub | ssh foo@192.168.1.20 'cat >> .ssh/authorized_keys'
foo@192.168.1.20's password:

Step 3: Set Permissions on – 192.168.1.20

Due to different SSH versions on servers, you might need to set permissions on the .ssh directory and the authorized_keys file.
[pi@raspbmc ~]$ ssh foo@192.168.1.20 "chmod 700 .ssh; chmod 640 .ssh/authorized_keys"
foo@192.168.1.20's password: [Enter Your Password Here]

From now onwards you can log into 192.168.1.20 as foo user from server 192.168.1.10 as pi user without password.
[pi@raspbmc ~]$ ssh foo@192.168.1.20

And now you can use scp to transfer files manually or you can automate transfer with script
scp file foo@192.168.1.20:/tmp

Monday, 13 January 2014

cURL timeout problem and solution

One page I made uses cURL to scrape small data from external web page. The problem I faced was when the page was offline for a while, my page did not load.

The fix I stumbled into was to add these three lines to my code.
 curl_setopt($ch, CURLOPT_TIMEOUT_MS, 5000);
 $curl_errno = curl_errno($ch);
 $curl_error = curl_error($ch);
 
Now my page still runs when the remote page is down and I get a error message.
 $url = $_GET['url'];
 $ch = curl_init();
 curl_setopt($ch, CURLOPT_URL, $url);
 curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 /* set timeout in ms */
 curl_setopt($ch, CURLOPT_TIMEOUT_MS, 5000);
 $data = curl_exec($ch);
 $curl_errno = curl_errno($ch);
 $curl_error = curl_error($ch);
 curl_close($ch);

 if ($curl_errno > 0) {
  echo "cURL Error ($curl_errno): $curl_error\n";
  } else {
  echo $match[0][0]);
  }
Tuesday, 26 November 2013

Vim editor is frozen after CTRL+S

Many programs and clients use CTRL+S to save documents. In VI and VIM it's quite different. Even though I still press CTRL+S by accident every once in awhile.
To “unfreeze” the console simply hit CTRL+Q

Apparently CTRL+S actually does XOFF, which means the terminal will accept key strokes but won’t show the output of anything. Press CTRL+Q to turn flow-control on (XON)

To disable keyboard listening to XOFFs, add this to your .bashrc (man stty for more options)
stty ixany
stty ixoff -ixon
If you need to send CTRL+S and/or CTRL+Q you can just add
stty stop undef
stty start undef
Monday, 18 November 2013

Capture images on webcam

I own a raspberry pi and have been thinking about getting the camera module, but still I haven't. One of the things I like to do is time lapse.
You can also do this with your web cam on your computer.

First check if your web cam is detected
$ ls -l /dev/video*
crw-rw----+ 1 root video 81, 0 nov 16 17:08 /dev/video0
Then install following programs
sudo apt-get install fswebcam
sudo apt-get install mencoder
Create your time lapse folder and use editor to create your tilme lapse file, the script.
mkdir timelapse
vim runtimelapse
Paste in the following:
#!/bin/bash
# Timelapse controller for USB webcam
frames=1440 # The numer of images to be taken
pause=10 # Dealy in seconds between images
DIR=~/timelapse
x=1
while [ $x -le $frames ]; do
filename=$(date -u +"%Y%m%d_%H%M-%S").jpg
fswebcam -d /dev/video0 -r 640x480 $DIR/$filename
x=$(( $x + 1 ))
sleep $pause;
done;
To make the script executable, use:
chmod 755 runtimelapse
Then run it using:
./runtimelapse
Now you have some number of images, time to create video
cd timelapse
ls *.jpg > list.txt
mencoder -nosound -ovc lavc -lavcopts vcodec=mpeg4:aspect=16/9:vbitrate=8000000 -vf scale=640:480 -o timelapse.avi -mf type=jpeg:fps=24 mf://@list.txt
And now you have time lapse video.

Instructions on making timelapse using raspberry pi


Thursday, 14 November 2013

Import csv to MySQL with php

I have small project at work where I need to import data from over 80 excel document and from more than one sheet from each into database. And I also needed to enter data from the web form to the database at the same time to identify each port with equipment and location. After converting sheet from .xls to .cvs I import the file by upload it trough the web form.
Not very hard task but I had some issues that I came a cross.
There is a simple method to import a file to database. From the command line I would do this.
mysql > LOAD DATA INFILE 'filename' INTO TABLE tablename FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\n' (field1,field2,field3);
Ok, this was easy but. In my case it seams that the file neaded to be in /var/lib/mysql/databasename for this command to work and I did not figure out how to get the file there when I uploaded it with php, guess it's permission issue and i'm not going to change them. Adding LOCAL to the command is the way to import the file from my directory, but it considered an administrative task and it returned error.

In the connection parameters I had to add "false,128" to get it to work.
$connect = mysql_connect("localhost","user","pass",false,128);

mysql_select_db("database",$connect);

 mysql_query("LOAD DATA LOCAL INFILE 'upload/$filename' INTO TABLE database FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\\n' (field1,field2,field3) set field4='value1',field5='value2';") ;
Now it works like a charm.
--cheers

See also how to export MySQL data to csv file 

ssh login takes too long time before prompt



I had this problem where it took way too long time for the prompt to appear when using ssh to remote server. And b.t.w. I am using my public ssh key. The GSSAPI authentication was timing out, and I'm not not relying on it.
To turn it off edit the /etc/ssh/ssh_config file with your favourite editor, I use VIM
sudo vim /etc/ssh/ssh_config
Edit this line and change from yes to no 
GSSAPIAuthentication no
Friday, 8 November 2013

Install and run a TFTP server


In some cases I need tftp server. The method to install the tftp server is very easy.

First install following packages.
$ sudo apt-get install xinetd tftpd tftp
Create /etc/xinetd.d/tftp and add code
service tftp
{
protocol        = udp
port            = 69
socket_type     = dgram
wait            = yes
user            = nobody
server          = /usr/sbin/in.tftpd
server_args     = /tftpboot
disable         = no
}
Create a folder  /tftpboot and modify privileges
$ sudo mkdir /tftpboot
$ sudo chmod -R 777 /tftpboot
$ sudo chown -R nobody /tftpboot
Restart the xinetd service.
$ sudo /etc/init.d/xinetd restart
Now the tftp server is up and running. For MAC OS X see: Run a TFTP Server on Mac OS X

Note:
My install was on Ubuntu 13.10

Edit:
Oct, 2014 installed on Mint 17


Wednesday, 6 November 2013

RewriteRule; Moved Permanently

I was getting high numbers of 404 "file not found" on my server do to discontinued blog's I hosted long a go. To reduce those numbers I used .htaccess to redirect all requests to another page using the 301, "Moved Permanently" code.

Example:
RewriteRule ^blogfolder\/?(.*)$ "http\:\/\/newdomain\.com\/" [R=301,L]
Live example:
http://acme.to/blogfolder/foo.html
Monday, 4 November 2013

Using history


I tend to forget commands, especially when they get longer or more complex. That's when "history" gets handy. You might want to search in history,
Example:
$ history | grep shutdown
1011  shutdown -h
1012  sudo shutdown -h now
This will give you all shutdown commands from your history. You can also check command history, without running it.
Example:
$ !yourcommand:p
Or if you need to execute multiple commands from history.
Example:
$ !219 ; !229 ; !221
The last example is how to list your most used commands.

$ history | awk '{a[$2]++}END{for(i in a){print a[i] " " i}}' | sort -rn | head



Simple things in live

I love Linux, In this first post here I'm going to show you two simple ticks that you will love if you do not know them already, and if you do know them I guess that you still love them.

No permission running command. For example you like to reboot in 10 minutes

$ shutdown -r 10
shutdown: Need to be root
You might be the one who repeats the command starting with "sudo" for root privileges, that's ok for short commands, but you might even want to use the really short one.
$ sudo !!
This will repeat your latest command as root.

The second trick is for same purpose with in the Vim editor. How often have you opened file for edit and when you try to save you find out tha you have no permission to save.
There is a sulution.
:w !sudo tee %
Quite simple and it works.