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: