Linux/Unix
[Linux/Shell/Bash] Count pattern matches/instances in string
by Chuck Kozler on Jan.20, 2010, under Computers, Linux/Unix, Networks/Servers, Programming, Web Dev
This handy little Bash scripting function will count the number of instances it finds in a string by the given delimeter. As of right now, its pretty basic…I didnt go too far into expanding it and working it (like going through and escaping all character escapes) and only escape for | and \.
function countPatterns { string_in="$1" delim="$2" if [ $delim == "/" ] || [ $delim == "|" ]; then delim="\\$delim"; fi retval=`echo $string_in | perl -ne 'while(/'${delim}'/g){++$count}; print "$count\n"'` return $retval }
Remember, this isnt really completed but you get the idea. The use is something like:
countPatterns "this|is|a|string|" "|" instances="$?" #would output 4 echo $instances
[VirtualBox/Linux/Windows] Copied Linux Guests Increasing eth devices
by Chuck Kozler on Jan.13, 2010, under Computers, Linux/Unix, Ubuntu, Windows
I noticed that when you copy Linux guests (VBoxManage clonevdi) and then try to use them, your ethernet device adapters keep increasing by one (eth0,eth1,eth2..etc).
This happens because the OS is looking in /etc/udev/rules.d/70-persistent-net.rules to look for the MAC address and corresponding adapter. Since the MAC address on the now new guest has been changed by VirtualBox, obviously the Guest OS can not find this MAC address. Naturally, it disables eth0 and creates eth1 with the new VirtualBox generated MAC address.
This can become quite troublesome, especially if you make a copy of a copy of a copy and so on.
I wrote a quick script to swap these MAC addresses around for you. I had to write something like this because I had to deploy about 20 Virtualized Guests and I created a base VDI to copy over and over as I needed it. I placed this script in the /root directory so I could just “su” and execute it, restart, and my address was fixed.
#!/bin/bash user=`whoami` if [ $user != "root" ]; then echo "You must be root to run this. Exiting." exit 300 fi function swapMacs { eth0_mac=`cat /etc/udev/rules.d/70-persistent-net.rules | grep -i "eth0" | cut -d ',' -f4 | cut -d '=' -f3 | cut -d '"' -f2 | sed -e 's/:/\\\\:/g'` if [ -z $eth0_mac ]; then echo " ! MAC Address for eth0 is empty. Could not retrieve MAC from udev file." exit 100 fi eth1_mac=`cat /etc/udev/rules.d/70-persistent-net.rules | grep -i "eth1" | cut -d ',' -f4 | cut -d '=' -f3 | cut -d '"' -f2 | sed -e 's/:/\\\\:/g'` if [ -z $eth1_mac ]; then echo " ! MAC Address for eth1 is empty. Could not retrieve MAC from udev file. ( Are you sure the line exists? )" exit 100 fi echo " * Find old mac: $eth0_mac" echo " * Replacing with: $eth1_mac" sed -i "s/$eth0_mac/$eth1_mac/g" /etc/udev/rules.d/70-persistent-net.rules if [ $? -eq 0 ]; then echo " + Successfully swapped mac addresses" echo " * Setting new udev file" new_rule=`cat /etc/udev/rules.d/70-persistent-net.rules | grep -i "eth0"` echo $new_rule > /etc/udev/rules.d/70-persistent-net.rules if [ $? -eq 0 ]; then echo " + We have successfully updated the udev file" else echo " ! Problem updating the udev file" exit 100 fi else echo " ! Problem swapping mac addresses" exit 100 fi } swapMacs
[Ubuntu/Linux] Set networking script
by Chuck Kozler on Dec.09, 2009, under Computers, Home, Linux/Unix, Networks/Servers, Ubuntu
Hi Everyone,
I have to manually change my network configuration settings a lot on my laptop when I’m at work and jumping between routers and other networks.
I got tired of manually entering all the commands so I wrote this. I expanded it a bit so other people can use it.
Its a quick and dirty script so it doesnt catch errors. Just checks if ifconfig and route commands were executed successfully.
Its pretty self explanitory. It takes in arguments of
device = the device you want to modify (eth0, eth1, etc…)
ip = the IP you want to set for yourself
gateway = The gateway you’re connecting to
dns = This is optional but you can set your own single DNS server address. If you do not enter one, the script will ask you if you want it to set you default ones with OpenDNS’ DNS server (http://opendns.org).
#!/bin/bash script_name=`basename $0` echo "" if [ "$1" == "--help" ] || [ "$1" == "-h" ]; then echo "Usage is: " echo "" echo " $script_name [device] [ip_addr] [gateway] [Optional: one_dns_server]" echo "" echo "Note: Only one DNS server can be set. Manually update resolv.conf if you want more" echo "Note: If no DNS is specified, the script will ask you if you want it to set you one." echo "" echo "" echo "Example: " echo "" echo " $script_name eth0 192.168.1.135 192.168.1.1 4.2.2.2" echo "" exit 0 fi device="$1" ip="$2" gw="$3" primary_dns="$4" user=`echo $USER` ans='y' if [ $user != "root" ]; then echo "You must be root to run this" exit 108 fi if [ -z $device ]; then echo "You must specify a device to modify" exit 5 fi if [ -z $ip ]; then echo "You must specify an IP address for your machine" exit 5 fi if [ -z $gw ]; then echo "You must specify a default gateway address" exit 5 fi if [ -z $primary_dns ]; then echo "* No DNS server set." echo "* You do not need to specify a DNS server but it is suggested" echo "* Would you like the script to write default DNS for you (using OpenDNS)? [y/n] (default: y)" read ans echo "Write DNS = " $ans fi # Do the networking configuration # ifconfig eth0 $ip if [ $? -eq 0 ]; then success=1 fi route add default gw $gw ret="$?" if [ $ret -eq 0 ] || [ $ret -eq 7 ]; then success=2 fi if [ ! -z $primary_dns ]; then su -c "echo nameserver $primary_dns > /etc/resolv.conf" else if [ $ans == 'y' ] || [ $ans == 'Y' ]; then su -c "echo nameserver 208.67.222.222 > /etc/resolv.conf" su -c "echo nameserver 208.67.222.220 >> /etc/resolv.conf" fi fi device_ip=`ifconfig eth0 | grep -i $ip | cut -d ':' -f2 | cut -d ' ' -f1` route_gw=`route -n | grep -i 192.168.155.1 | awk '{ print $2 }'` route_flag=`route -n | grep -i 192.168.155.1 | awk '{ print $4 }'` if [ $success -eq 2 ]; then echo "" echo "* Success!" echo "" echo "* IP: $device_ip" echo "* Gateway: $route_gw ( $route_flag )" echo "" fi exit
[Gentoo] VirtualBox/VMWare Networking pcnet32
by Chuck Kozler on Oct.07, 2009, under Computers, Home, Linux/Unix, Networks/Servers
So, personally, I have never really had to install Gentoo in a Virtualized environment so normally my networking and everything has worked right out of the box from the basic kernel configurations selected when you run “make menuconfig”.
Unbeknown to me, that would not at all be the case when you virtualize Gentoo with VMWare or VirtualBox. As some of you may know, VMware and VirtualBox both use a pcnet32 driver/module to enable networking. Now, after a ton of googling and back and forth I finally figured out what you have to do.
When you execute “make menuconfig”
make menuconfigThen, when you’re prompted with the options, step through the menu as such
Device Drivers
|----------> Network Device Support
|---------------> [ * ] Ethernet (10 or 100mbit)
|--------->[ * ] AMD PCNet32 PCI Support
Make sure you press “Y” to include it rather than modularize it (unless you have an initrd.img setup and want/need to modularize it) so this way you dont have to worry about editing
/etc/modules.autoload.d/
or having to do anything else for that matter to get networking working with the virtualized network/ethernet adapters
Then
# make -j2 # cp /usr/src/linux/arch/x86/boot/bzImage /boot/kernel # reboot
[Ubuntu\Mono\Gnome] GtkMountISO Application Release
by Chuck Kozler on Sep.27, 2009, under Computers, Home, Linux/Unix, Programming, Ubuntu, Windows
So, I guess this is my actual first application release in about 4 years since I stopped writing cheats/hacks for Counter-Strike and Counter-Strike source. You can see the video of this in action below and underneath, a link to download it from. You can find all the information you need in the readme. Please, make sure you read the readme, it will save us all a lot of time. For whatever reason, I am going to post the flow chart I made for the bash installer script. Maybe *someone* can find it useful in the future.
Sphere: Related Content[Ubuntu/Gnome] Gtk ISO Mount Program
by Chuck Kozler on Sep.24, 2009, under Computers, Home, Linux/Unix, Programming, Ubuntu
This is a program I wrote to mount ISO’s under Linux. I wrote it in C# utilizing the Mono libraries. I must say, I love C# so much more now. The video is below and the unedited/uncleaned code is below the video. Hope you enjoy!
using System; using Gtk; using System.Diagnostics; using System.Text.RegularExpressions; public partial class MainWindow: Gtk.Window { string Users_Home = Environment.GetEnvironmentVariable( "HOME" ); public int runCommand( string command, string args, bool wait ) { Process proc = new Process( ); proc.StartInfo.FileName = command; proc.StartInfo.Arguments = args; proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardError = true; proc.StartInfo.RedirectStandardOutput = true; if( proc.Start() ) { if( wait == true ) { proc.WaitForExit( ); return proc.ExitCode; } else { return proc.ExitCode; } } return -1; } public void runCommand( string command, string args, bool wait, int milliseconds ) { Process proc = new Process( ); proc.StartInfo.FileName = command; proc.StartInfo.Arguments = args; proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardError = true; proc.StartInfo.RedirectStandardOutput = true; if( proc.Start() ) { if( wait == true ) if( milliseconds > 0 ) proc.WaitForExit( milliseconds ); else proc.WaitForExit( ); else proc.Close( ); } } public string getOutput( string command, string args, bool wait ) { Process proc = new Process( ); proc.StartInfo.FileName = command; proc.StartInfo.Arguments = args; proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardError = true; proc.StartInfo.RedirectStandardOutput = true; if( proc.Start( ) ) { if( wait == true ) { proc.WaitForExit( ); string output = proc.StandardOutput.ReadToEnd( ).TrimEnd( ); string error = proc.StandardError.ReadToEnd( ).TrimEnd( ); if( output.Equals( "" ) || output.Equals( " " ) ) { return error; } else return output; } else { string output = proc.StandardOutput.ReadToEnd( ).TrimEnd( ); string error = proc.StandardError.ReadToEnd( ).TrimEnd( ); if( output.Equals( "" ) || output.Equals( " " ) ) { return error; } else return output; } } else return "Could not start process. Check process file name."; } public string getCommand( string command_name ) { return getOutput( "which", command_name, false ); } public void UpdateMountList( ) { runCommand( "sh", "-c \"mount -l | grep -i \"" + Users_Home + "/.GtkMountISO\" | cut -d ' ' -f3 > " + Users_Home + "/.GtkMountISO/mounts.current\"", true ); int ln_count = 0; string cur_line = ""; System.IO.StreamReader file = new System.IO.StreamReader( Users_Home + "/.GtkMountISO/mounts.current" ); while( ( cur_line = file.ReadLine( ) ) != null ) { CurrentMounts.AppendText( cur_line ); ln_count++; } file.Close( ); CurrentMounts.RemoveText( ln_count ); } public MainWindow (): base (Gtk.WindowType.Toplevel) { Build (); if( !( System.IO.Directory.Exists( Users_Home + "/.GtkMountISO" ) ) ) { //If hidden GtkMountISO folder does not exist, create dir string mkdir = getCommand( "mkdir" ); Console.WriteLine( "GtkMountISO folder does not exist. Creating." ); int retval = runCommand( mkdir, Users_Home + "/.GtkMountISO", true ); if( retval == 0 ) { Console.WriteLine( "Created directory for GtkMountISO" ); } } else { UpdateMountList( ); } } protected void OnDeleteEvent (object sender, DeleteEventArgs a) { int rm_retval = runCommand( "rm", Users_Home + "/.GtkMountISO/mounts.current", true ); Console.WriteLine( "Del retval = " + rm_retval ); Application.Quit (); a.RetVal = true; } protected virtual void OnMountISOClicked (object sender, System.EventArgs e) { string zenity = getCommand( "zenity" ); string xterm = getCommand( "xterm" ); string echo = getCommand( "echo" ); string sleep = getCommand( "sleep" ); try { /* * 1.) Get Filename */ //Get Full file name string ISO_Name = SelectISOButton.Filename.ToString( ); Regex r = new Regex( @"\s+" ); string ISO_Name_Regex = r.Replace( ISO_Name, @"\\ " ); //Split it based on slashes string[] ISO_Name_Parts = ISO_Name.Split( '/' ); //Get length to subtract one and get single file name int Parts_num = ISO_Name_Parts.Length; string ISO_Parsed_Name = ISO_Name_Parts[ Parts_num - 1 ]; //Split string again based on "." to get standalone file name with no extension string[] ISO_Strip_Extension = ISO_Parsed_Name.Split( '.' ); int ISO_Parsed_Num = ISO_Strip_Extension.Length; string ISO_Cleaned_Name = ISO_Strip_Extension[ ISO_Parsed_Num - 2 ]; string iso_extension = ISO_Strip_Extension[ ISO_Parsed_Num - 1 ]; Console.WriteLine( "Extension = " + iso_extension ); if( iso_extension.Equals( "iso" ) || iso_extension.Equals( "ISO" ) ) { Console.WriteLine( "Cleaned Name = " + ISO_Cleaned_Name ); /* * 2.) Make folder name @ /_USERS_HOME_DIR_/_FILE_NAME_ */ string Users_Home = Environment.GetEnvironmentVariable( "HOME" ); Console.WriteLine( Users_Home ); string mkdir = getCommand( "mkdir" ); string make_dir_cmd = mkdir + " " + Users_Home + "/.GtkMountISO/" + ISO_Cleaned_Name; Console.WriteLine( make_dir_cmd ); int make_dir = runCommand( mkdir, Users_Home + "/.GtkMountISO/" + ISO_Cleaned_Name, true ); string mount_point = Users_Home + "/.GtkMountISO/" + ISO_Cleaned_Name; int zenity_retval = -1; if( make_dir != 0 ) { zenity_retval = runCommand( zenity, "--question --text=\"Folder exists. Would you like to mount anyway?\"", true ); Console.WriteLine( "Zenity reval = " + zenity_retval ); } if( ( make_dir == 0 ) || ( make_dir != 0 && zenity_retval == 0 ) ) { Console.WriteLine( "Folder created" ); /* * 3.) Execute "mount -t iso9660 _FULL_FILE_NAME_ /_USERS_HOME_DIR_/_FILE_NAME_ -o loop */ string gksudo = getCommand( "gksudo" ); string mount = getCommand( "mount" ); Console.WriteLine( "ISO_Name = " + ISO_Name ); Console.WriteLine( "Mount_Point = " + mount_point ); //Need to some how account for white space without corrupting the commands sent to the system... int retval = runCommand( gksudo, "\"" + mount + " -t iso9660 " + ISO_Name_Regex + " " + mount_point + " -o loop\"", true ); Console.WriteLine( " Mount Retval = " + retval ); if( retval == 0 || retval == 1 ) { //Success if( zenity.Equals( "" ) ) { runCommand( xterm, "-e \"" + echo + " Success! && " + sleep + " 5\"", true, 0 ); } else runCommand( zenity, "--info --title=\"Success\" --text=\"Success!\n\n You can find the ISO mounted at " + mount_point + "\"", true, 0 ); string nautilus = getCommand( "nautilus" ); if( nautilus.Equals( "" ) ) return; else runCommand( nautilus, "\"" + mount_point + "\"", false, 0 ); } else if( retval == 7 ) { //Mount Failure if( zenity.Equals( "" ) ) { runCommand( xterm, "-e \"" + echo + " Failed to mount. Is the file an actual ISO? && " + sleep + " 5\"", true, 0 ); } else runCommand( zenity, "--error --title=\"error\" --text=\"Failed to mount. Is the file an actual ISO?\"", true, 0 ); } else if( retval == 32 ) { //Mount Failure if( zenity.Equals( "" ) ) { runCommand( xterm, "-e \"" + echo + " Failed to mount. Is there already something mounted there? && " + sleep + " 5\"", true, 0 ); } else runCommand( zenity, "--error --title=\"error\" --text=\"Failed to mount. Is there already something mounted there?\"", true, 0 ); } /* * 4.) Add to flat file database of mounted folders */ UpdateMountList( ); } } else { if( zenity.Equals( "" ) ) { runCommand( xterm, "-e \"" + echo + " File is not an ISO image && " + sleep + " 5\"", true, 0 ); } else runCommand( zenity, "--error --title=\"error\" --text=\"You must select an ISO image file\"", true, 0 ); } } catch( NullReferenceException nullexception ) { string error = nullexception.ToString( ); if( zenity.Equals( "" ) ) { runCommand( xterm, "-e \"" + echo + " You must select a file first && " + sleep + " 5\"", true, 0 ); } else runCommand( zenity, "--error --title=\"error\" --text=\"Error Thrown: \n\n" + error + "\n\nYou must select a file first\"", true, 0 ); Console.WriteLine( error ); } } protected virtual void OnUnMountISOClicked (object sender, System.EventArgs e) { Console.WriteLine( "Unmounting " + CurrentMounts.ActiveText ); string zenity = getCommand( "zenity" ); string xterm = getCommand( "xterm" ); string echo = getCommand( "echo" ); string sleep = getCommand( "sleep" ); string gksudo = getCommand( "gksudo" ); string umount = getCommand( "umount" ); string iso_to_unmount = CurrentMounts.ActiveText; int umount_retval = runCommand( gksudo, "\"" + umount + " -f " + iso_to_unmount + "\"", true ); Console.WriteLine( "Umount retval = " + umount_retval ); if( umount_retval == 0 ) { if( zenity.Equals( "" ) ) { runCommand( xterm, "-e \"" + echo + " File successfully unmounted && " + sleep + " 5\"", true, 0 ); } else runCommand( zenity, "--info --title=\"error\" --text=\"File successfully unmounted!\"", true, 0 ); } UpdateMountList( ); } }
[Ubuntu/Wine] Windows Installer Service Could Not Be Accessed
by Chuck Kozler on Aug.27, 2009, under Computers, Linux/Unix, Ubuntu
I have noticed running Wine version 1.1.28 and trying to install some programs and/or games returned the error
“The Windows Installer Service could not be accessed. This can occur if you are running Windows in safe mode, or if the Windows Installer is not correctly installed. Contact your support personnel for assistance.”
This is how I went about fixing it:
1.) Download “winetricks” from here => http://wiki.winehq.org/winetricks – more specifically, you can execute this command:
wget http://www.kegel.com/wine/winetricks
2.) Execute winetricks
sh winetricks3.) Scroll down until you see “msi2″ and put a check next to it. This will install the Microsoft Installer version 2.0 for wine.
4.) Execute the command “winecfg”
winecfg
5.) Scroll down until you see msi(native, builtin)
6.) Click it and click the “edit” button to the right
7.) Click the radio button next to “Builtin then Native”
For whatever reason, this fixed the above problem for me. If it doesnt for you, let me know what problems you encountered.
Sphere: Related Content[Mono/Linux] C# Shell Commands
by Chuck Kozler on Mar.24, 2009, under Computers, Home, Linux/Unix, Programming, Windows
These are some functions I have wrote recently for more or less debugging purposes. I use these functions to execute shell commands via C#. I am in no way a professional programmer so my code may seem sloppy, redundant, or plain useless to some. Thank you, but, please keep those comments to yourself.
What the function does is pretty much explained in the function definitions.
public string logfile = "debug.log"; public void writelog( string logfile, string message ) { string datetime = System.DateTime.Now.ToString(); if( !File.Exists( logfile ) ) runshellcmd( "touch " + logfile ); StreamWriter file = new StreamWriter( logfile, true ); file.WriteLine( "[ " + datetime + " ]:\n" + message + "\n" ); file.Close( ); } public int runshellcmd( string cmd ) { string[] parts = cmd.Split( ' ' ); string cmd_name = parts[ 0 ]; string arguments = ""; if( parts.Length > 1 ) for( int i = 1; i < parts.Length; i++ ) arguments += " " + parts[ i ]; Process proc = new Process( ); proc.StartInfo.FileName = cmd_name; proc.StartInfo.Arguments = arguments; proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardError = true; proc.StartInfo.RedirectStandardOutput = true; try { if( proc.Start( ) ) { proc.WaitForExit( ); return proc.ExitCode; } else return proc.ExitCode; } catch( System.ComponentModel.Win32Exception w32e ) { writelog( logfile, w32e.Message.ToString( ) ); return proc.ExitCode; } } public string getoutput( string cmd ) { string[] parts = cmd.Split( ' ' ); string cmd_name = parts[ 0 ]; string arguments = ""; if( parts.Length > 1 ){ for( int i = 1; i < parts.Length; i++ ){ arguments += " " + parts[ i ]; } } Process proc = new Process( ); proc.StartInfo.FileName = cmd_name; proc.StartInfo.Arguments = arguments; proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardError = true; proc.StartInfo.RedirectStandardOutput = true; try { if( proc.Start( ) ) { proc.WaitForExit( ); string output = proc.StandardOutput.ReadToEnd().TrimEnd(); string error = proc.StandardError.ReadToEnd().TrimEnd(); if( output.Equals( "" ) || output.Equals( " " ) ) return error; else return output; } } catch( System.ComponentModel.Win32Exception w32e ) { string ret = "Error Thrown: " + w32e.ToString( ); return ret; } return "Broke"; } public bool pipeoutput( string ofile, string cmd ) { StreamWriter file = new StreamWriter( ofile ); try { file.WriteLine( getoutput( cmd ) ); file.Close( ); return true; } catch( System.IO.FileNotFoundException notfound ) { writelog( logfile, notfound.Message.ToString( ) ); return false; } } public string getexitcode( string cmd ) { return runshellcmd( cmd ).ToString(); } public string pwd( ) { string ret = getoutput( "pwd" ); return ret; } public bool killbypid( int pid ) { if( runshellcmd( "kill -9 " + pid ) == 0 ) return true; else return false; } public bool killbyname( string procname ) { //This should actually be "killall -9 + procname", I placed mono in the front because I was killing my own process. Remove to kill other processes by name if( runshellcmd( "killall -9 mono " + procname ) == 0 ) return true; else return false; } public string mygrep( string cmd_to_pipe, string text_to_search ) { string output = ""; //Check if the file exists if( File.Exists( "grep_tmp" ) ) runshellcmd( "rm grep_tmp" ); //Pipe output to a temp file if( pipeoutput( "grep_tmp", cmd_to_pipe) ) { //Set the out variable to the output of the command output = getoutput( "grep -i " + text_to_search + " grep_tmp" ); //Delete the file if( runshellcmd( "rm grep_tmp" ) == 0 ) { //Return the results return output; } } return ""; }
These are some example uses. Stuff I used when debugging.
//Delete the logfile to just make sure I was viewing the most current stuff runshellcmd( "rm " + logfile ); //get workingdir by running the pwd command and returning the output (see pwd() function) string workingdir = pwd( ); //Get processID int procid = System.Diagnostics.Process.GetCurrentProcess().Id; //Get processname string procname = System.Diagnostics.Process.GetCurrentProcess().ProcessName; writelog( logfile, "Working Dir: " + workingdir ); writelog( logfile, "Process ID: " + procid ); writelog( logfile, "Process Name: " + procname ); //We want to search for "process" after we pipe the output from debug.log string tmp = mygrep( "cat debug.log", "process" ); writelog( logfile, "Grep Results:\n" + tmp ); textview1.Buffer.Text = getoutput( "cat debug.log" ); //Kill our process by PID killbypid( procid ); //Kill by our process name killbyname( procname );
[Bash] Stop hddtemp/Conky populating netstat
by Chuck Kozler on Mar.17, 2009, under Computers, Linux/Unix, Ubuntu
Hi everyone,
I noticed when using Conky and hddtemp application that most conky scripts will query hddtemp through
nc localhost <hddtemp_port>
and would populate netstat command with a whole ton of TIME_WAIT connections. I have developed a fix for this.
1.) First, edit the hddtemp script where you report the temperature to look something like this:
Temperature: ${alignr}${exec cat /etc/hddtmp_out }
Then:
sudo touch /etc/hddtmp_out
Then, utilize this script or create a simliar one to generate the same effects:
#!/bin/bash date=`date` touch /root/gettemp.log #change your harddrive to /dev/sda1 if it is not /dev/sda1 /usr/sbin/hddtemp /dev/sda1 | cut -d ":" -f3 > /etc/hddtmp_out if [ $? -eq 0 ]; then echo "Command completed successfully" elif [ $? -gt 0 ] || [ $cmd != " " ]; then echo "Caught error" fi #temp=`hddtemp /dev/sda1 | cut -d ":" -f3` #log=`echo Get temp finished @ $date reporting $temp >> /root/gettemp.log` exit 0
What this script does:
First it gets the date and touches gettemp.log in /root/ to ensure it is there. Then, it executes the hddtemp executable querying the appropriate hard drive. Make sure to change to your appropriate hard drive (read hddtemp manual). The script then parses out the temperature and outputs it to /etc/hddtmp_out (hint: cat /etc/hddtmp_out from the conky script). Finally, for logging and error reporting purposes, it outputs to the gettemp.log file in the root directory. This was more or less used when I was debugging so you can remove it if you like. You can place that in /usr/local/bin for easy access as that is how I created the cron job (read below). Also, if you notice that your conky script is not updating, remove the comments next to the two lines for logging so you can see if it is in fact writing to the file at the write times (every minute).
Then create a cron job to run every minute. This wont be too intensive on the system seeing as to query the temperature through the cron job is about as equal as running the netcat command.
sudo su - crontab -e
Add this line:
* * * * * test -x /usr/local/bin/gettemp && ( sudo /usr/local/bin/gettemp )
This will create a cron job to execute every minute to report and output to the hddtmp_out file in /etc.
Sphere: Related Content[Linux/Bash] Update DNS Script
by Chuck Kozler on Mar.04, 2009, under Computers, Linux/Unix, Networks/Servers, Ubuntu
I am currently doing a project that involves me creating my own DNS servers in virtual environments. To utilize those DNS servers I will need to, of course, edit the host computer’s /etc/resolv.conf to point to my new DNS servers IP addresses. For some odd reason I could not set a static IP (my Universities network is complete crap) and I required the dhclient/dhcp3-client package to be able to utilize my network. Since dhcp3-client likes to overwrite the /etc/resolv.conf file (regardless of what is in the /etc/dhcp3/dhcp.conf file) I had to hand edit the /etc/resolv.conf file ALL the time. Well, I got sick of that and this is what came of it.
I hope you enjoy
#!/bin/bash user=`whoami` if [ $user != "root" ]; then echo "You must be root to run this" exit 0 fi basename=`basename $0` location=`dirname "$0"` ans='n' if [ $location != "/usr/local/bin" ]; then echo "" echo "If this were in /usr/local/bin then it would be easier to use (or set PATH variables)" echo "" echo "Would you like to copy it there? [Y/n]" read ans fi function usage { echo " " echo "Usage is: " echo " " echo " makedns <domain> <domain_to_search> <ip_of_dns_1>" echo " " echo " " echo "Example:" echo " " echo " makedns test.local test.local 192.168.1.101" echo " " } if [ -z "$1" ] || [ -z "$2" ] || [ -z "$3" ] ; then usage if [ -z "$1" ];then echo "You left field 1 blank. Please fill in a DNS domain name" elif [ -z "$2" ]; then echo "You left field 2 blank. Please fill in a DNS search to search" elif [ -z "$3" ]; then echo "You left field 3 blank. Please fill in a primary DNS IP" fi echo " " exit 0 fi # # TODO: Possibly do this in a loop and store them in an array? # lines=`wc -l /etc/resolv.conf | cut -d " " -f1` dnsdomain=`sed -n "1 p" /etc/resolv.conf | cut -d " " -f2` dnssearch=`sed -n "2 p" /etc/resolv.conf | cut -d " " -f2` dnsip1=`sed -n "3 p" /etc/resolv.conf | cut -d " " -f2` dnsip2=`sed -n "4 p" /etc/resolv.conf | cut -d " " -f2` _in_dnsdomain="$1" _in_dnssearch="$2" _in_dnsip1="$3" _in_dnsip2="$4" # # # #echo text_to_pipe | sed s/<old>/<new> complete=0 if [ $lines -gt 0 ]; then echo "domain $_in_dnsdomain" > /etc/resolv.conf if [ $? -eq 0 ]; then complete=1 fi echo "search $_in_dnssearch" >> /etc/resolv.conf if [ $? -eq 0 ]; then complete=2 fi echo "nameserver $_in_dnsip1" >> /etc/resolv.conf if [ $? -eq 0 ]; then complete=3 fi if [ $_in_dnsip2 != "" ]; then echo "nameserver $_in_dnsip2" >> /etc/resolv.conf fi if [ $complete -ge 3 ]; then echo "DNS update/reconfiguration complete and successful." echo " " echo "New Configuration: " echo " " cat /etc/resolv.conf echo " " echo "Exiting." fi fi #If they want to move it or not to /usr/local/bin if [ $ans == "y" ] || [ $ans == "Y" ]; then echo "Moving..." cp $basename /usr/local/bin/ chmod 755 /usr/local/bin/$basename fi
