Scripting in Axis Network Cameras and Video Servers
Table of Contents 1 INTRODUCTION .............................................................................................................5 2 EMBEDDED SCRIPTS ....................................................................................................6 2.1 2.2 PHP .....................................................................................................................................6 SHELL .........................................................................................
5.3.11 echo................................................................................................................................47 5.3.12 env..................................................................................................................................47 5.3.13 expr ................................................................................................................................47 5.3.14 false........................................................................
5.5 USING VARIABLES .............................................................................................................64 5.6 BUILT-IN SHELL VARIABLES ............................................................................................64 5.7 THE IMPORTANCE OF QUOTATION MARKS .....................................................................65 5.8 THE TEST COMMAND ........................................................................................................66 5.8.
Introduction 1 Introduction This document is intended as a guide for application developers and describes how to use scripting in Axis Network Cameras and Video Servers. The reader is presumed to have prior knowledge of shell scripting, and also of Linux/Linux systems in general. The document provides numerous examples of ready-made scripts that were written for the most common applications. These scripts can be used for your own purposes, after making the changes required by your particular application.
Embedded Scripts 2 Embedded Scripts The embedded scripts that can be used in Axis camera and video server products can be of 2 different types: shell scripts or PHP3 scripts. These scripts can be used for many different purposes and can, for example, start the buffering of images or the uploading of files via FTP or SMTP. Scripts can be run in several different ways. One example is when the built-in Task Scheduler in the Axis products is used to start programs or scripts when certain events occur.
Embedded Scripts PDF functions Math functions Axis recommends checking that PHP3-Lite supports the functions required before creating custom scripts. Consult the PHP3-Lite manual on our Web site at: www.axis.com 2.2 Shell A shell is a command processor or interpreter that reads and executes the commands entered by the user. A shell is also a programming language in which programs can be written for the shell to interpret. These programs are therefore known as shell scripts.
Using scripts in Axis Camera/Video products 3 Using scripts in Axis Camera/Video products This document contain examples of complete scripts that can be used as they are, or after being modified to suit your own purposes. The scripts have been written for the most common applications. Some of these scripts require a task.list file, and these are also provided.
Using scripts in Axis Camera/Video products 3.2.1 Syntax for /etc/task.list An entry in /etc/task.list has the following syntax: %:; = is the event description = is the program to start = are the arguments to be passed to . The maximum number of events is 64. An event description should contain one or more of the following definitions. Definition [hh:mm-hh:mm] time( h(...) m(...) s(...) ) [dd/mm-dd/mm] date( w(...) m(...) d(...
Using scripts in Axis Camera/Video products IMPORTANT! The default behavior when an event is triggered is that the program runs, exits and starts again, for as long as the triggering event is valid. once Specifying once tells utask to skip starting the program as long as the event has not been invalidated. Utask checks for events ten times a second (if not in standby mode). Thus, if an event is specified to run at a certain point in time, e.g.
Using scripts in Axis Camera/Video products 3.2.1.2 Example of a task.list # Execute the alarm_ftp_net script if a positive transition is detected on the Input # Output 0 every day of the week date(w(0,1,2,3,4,5,6)) pattern ((IO0:/)) immune once % /etc/alarm_ftp_net : CAM1 IO0; # FTP transfer once every 15 minutes, uninterrupted using alarm_ftp_net script. time(m(0,15,30,45)) immune once % /etc/alarm_ftp_net : CAM1 IO0; # Sends an alert message every time I1 and I2 are high at the same time...
Using scripts in Axis Camera/Video products Running Scripts via Telnet For development purposes, it may be convenient to connect to the camera/video Server via Telnet. Depending on which product is used, this is either enabled by default and uses authentication, or it can be enabled by editing the /etc/inittab. If the product requires editing of the /etc/inittab there will be no authentication for the Telnet connection and no password will be required for access.
Using scripts in Axis Camera/Video products Restart the video server and it will now be accessible via Telnet. To activate the script via Telnet, follow the instructions below. For a shell script: activate the script by typing e.g. ./ For a PHP3 script: type e.g. php An example of a Telnet Session 3.4 Included Helper Applications This section explains some of the applications shipped with the Axis camera/video servers.
Using scripts in Axis Camera/Video products 3.4.1.1 Options The valid parameters for bufferd are: Option -start -reset -stop -d -buffername -uri -postdelay -predelay -pre -post -format -snapshot -immediate Description Start a buffer. Remove a buffer. Stop a buffer. Start as a daemon. This option should only be used when starting up from initd, or when the first instance is to be started.
Using scripts in Axis Camera/Video products • %M (minute) • %S (second). These correspond to the date and time the file was created. Also supported is %i, which specifies the file number, and which also can be followed by a number specifying how many digits are allowed. The default format is snapshot_%y%m%d_%H%M%S_%i4. 3.4.1.3 Examples The first example shows how to take one (1) image with camera one (1).
Using scripts in Axis Camera/Video products (This starts the buffer and can be specified in a start-up script or as an event or utask) When an event occurs, as specified for utask (see below) the following command sequence is used to handle the buffer: bufferd -stop ALARM { handle images} bufferd -reset ALARM bufferd -start -buffername ALARM -uri ftp://axis-cgi/jpg/1/176x144.
Using scripts in Axis Camera/Video products 3.4.3 smtpclient This client is used for SMTP connections. You can send e-mail with attached files and specify a range of common parameters, i.e.; subject, address of the sender for the replies, address to send copy to , etc. A typical example is to send an e-mail with snapshots when an alert is detected. Usage: smtpclient [options] recipients... Option -M Description Subject line of message. Address of the sender. Address of the sender for replies.
Using scripts in Axis Camera/Video products 3.4.4 shttpclient This client is used for HTTP connections. Its main uses are; • for sending alarm notifications to a remote web server by simply accessing a URL with a CGI-script • for uploading images/files via HTTP • for sending dynamic information such as when a IP-number is received via DHCP The shttpclient supports basic authentication for web servers and proxy servers.
Using scripts in Axis Camera/Video products 3.4.5 statusled Usage: statusled Set the status-led color, where is one of the following: • • • • 'off' 'green' 'yellow' 'red' The indicator flashes briefly and briefly displays orange during the start-up and self-test routines. The indicator then displays green to indicate a healthy unit status. Red will be displayed only if a problem has occurred. Axis Communications AB provides NO support for application development of any kind.
An Introduction to PHP3 4 An Introduction to PHP3 PHP3 is a server-side HTML-embedded scripting language. A simple answer, but what does this mean? An example: 1 2 3
4 Example 5 6 7 8 9 10 Notice how this is different from a CGI script written in other languages such as Perl or C.An Introduction to PHP3 4.1.1 alert.lib This script implements a function that connects to a host and leaves a message. This function requires an application that can handle the alert to be running on the contacted host. function alert($host,$protocol,$port,$message) { ... } Parameter $host $protocol $port $message Description (not null) The host-name or address to send the alert to. Specify the protocol (0 = TCP, 1 = UDP). Default is 0. The port to connect to. Default is 15.
An Introduction to PHP3 Parameter $passive_mode Description Choose passive mode. on or off. In passive mode, data connections are initiated by the client, rather than by the server. On errors, the function returns one of the following: • 1 (connection failed) • 2 (login failed) • 3 (upload failed) • 4 (parameter error) • 5 (could not set passive mode) Parameter errors occurs when any of $host, $user, $pass, $source or $destination is unspecified, or when the parameter $suffix has an invalid value. 4.1.
An Introduction to PHP3 Although the argument $file can be left unspecified, this is NOT recommended, as this sets smtpclient to interactive mode and thus locks the execution of PHP. On error, the function returns 1 (no sender specified) or 2 (no recipient specified) Otherwise the function returns 0. 4.1.5 ppp.lib These functions allow a PHP3-script to control the use of ppp connections through the pppwrapper. function ppp_getpid() { ... } Called from ppp_start() and ppp_stop().
An Introduction to PHP3 Called from ppp_offline(). Sends SIGUSR2 (12) to the currently running pppwrapper. If the wrapper isn't running, the function returns –1 and an error is logged in the syslog. function ppp_online($behavior, $max_attempt, $ppp_interval) { ... } Initializes the ppp connection. Returns 1 if the connection is established, -1 for errors and logs the error in the syslog.
An Introduction to PHP3 $passive_mode="on"; shoot(); $res = ftp($host, $user, $pass, $time, $delay, $source, $destination, $suffix, $countermax, $startcount, $port, $passive_mode); if($res == 1) { log("upload script } else if($res == 2) { log("upload script } else if($res == 3) { log("upload script } else if($res == 4) { log("upload script } else if($res == 5) { log("upload script } ?> - Could not connect to host"); - Could not log on to host"); - Could not put the file"); - something wrong with param
An Introduction to PHP3 4.2 PHP3 script examples The complete PHP3 scripts shown here can be used for the most common applications. The scripts can also be downloaded from the Axis web site at www.axis.com. PHP Scripting Tips • To use a browser for debugging your scripts, write the log messages as html.
An Introduction to PHP3 4.2.1.1 Driver.php3 The script moves the camera according to the button pressed by the user. The HTML interface sends a single parameter to the script: the number of the button pressed. The appropriate data is sent to the serial port, according to the number/button pressed. The script uses the HTTP-API (available on www.axis.com) to write data to the serial port. switch($param) // Move the camera according to the button pressed { case 1: // Up Left fopen("http://127.0.0.
An Introduction to PHP3 break; case 6: // Down fopen("http://127.0.0.1/axiscgi/com/serial.cgi?port=1\&write=FF020010003F51","w"); usleep(100000); // Wait 0.1 seconds fopen("http://127.0.0.1/axiscgi/com/serial.cgi?port=1\&write=FF020000000002","w"); break; case 7: // Down Left fopen("http://127.0.0.1/axiscgi/com/serial.cgi?port=1\&write=FF020010003F51","w"); fopen("http://127.0.0.1/axiscgi/com/serial.cgi?port=1\&write=FF0200043F0045","w"); usleep(100000); // Wait 0.1 seconds fopen("http://127.0.0.
An Introduction to PHP3 4.2.2 Example 2 – FTP Upload of Images This script will upload 2 pre-alarm and 2 post-alarm images via FTP. It is fairly general and may be used in many different configurations. 4.2.2.1 The task.list once immune % /bin/bufferd : -start -buffername CAM1 -pre 2 -post 2 -predelay 1000 -postdelay 1000 -uri ftp://jpg/1/352x288.jpg; date(w(0,1,2,3,4,5,6)) pattern((IO0:/)) immune once % /bin/sh : -c php /etc/httpd/html/alarm_ftp_net.php3; The first entry in the task.
An Introduction to PHP3 The second part of the script is where it all happens: 1 2 3 4 5 All pre/post alarm buffers previously started by utask are stopped. Waits until all post-alarm images are stored. FTP transfer of all images. Restart of pre/post alarm buffers. Exit. for($c=0;$c<(strlen($sources));$c++) { // Stop the, by utask, //started buffers $command="bufferd -stop -buffername ".$buffer_prefix.
An Introduction to PHP3 //directory if(($file_name != ".") &&($file_name != "..")) { // That is a regular file $file = "/tmp/".$buffer_prefix.substr($sources,$i ,1)."/".$file_name; $destination_name = $destination . $buffer_prefix.substr($sources,$i,1); $destination_name .= strchr($file_name,"_"); //extract timestamp from //src, append to dst if(!ftp_put($session, $destination_name, $file, FTP_BINARY)) { // Upload that file to the //FTP server error_log("Could not upload file ".$file." as ".
An Introduction to PHP3 4.2.3 Example 3 – FTP and E-mail on Event This script will upload 2 pre-alarm and 2 post-alarm images via FTP and also send an e-mail as notification of the event. In addition to the parameters in example 1, the following parameters are added: $smtp_server = "mail.somewhere.com";// The server to use as mail server $subject = "'Alarm trigged'"; // The subject to use in the mail $from = "someone@somewhere.com"; // The specified sender $reply = " someone1@somewhere.
An Introduction to PHP3 4.2.4 Example 4 – Sequential FTP Upload When input 0 goes high, this script will, for 10 seconds, upload images via FTP, at 2 second intervals. The uploaded images can be named by specifying a suffix. These can be date, incremental sequence number or limited sequence (overwrites files when maximum is reached). The parameters come first: $buffer_prefix = "SNAP"; $sources = "1"; $image_format = "fullsize"; $delay = 2000; $file_format = "snapshot"; $ftp_server = "10.13.9.
An Introduction to PHP3 The script itself follows: error_reporting(E_ALL); function conv($value) { // A function for converting //single digit integers into //two digit integers if($value < 10) { $value = "0$value"; } return strval($value); } for($c=0;$c<(strlen($sources));$c++) { // Start the buffers as //specified by the parameters //above //$command="bufferd -reset -buffername //".$buffer_prefix.substr($sources,$c,1); //system($command); $command="bufferd -start -buffername "; $command.
An Introduction to PHP3 $session = ftp_connect($ftp_server, $port); if($session) { // Connection successfully //established if(ftp_login($session, $user, $pass)) { // Successful login attempt if (!ftp_pasv($session, $passive_mode == "yes")) { ftp_quit($session); error_log("Could not set passive mode",0); } else { // Passive mode successfully //set $start_time = gettimeofday(); $current_time = $start_time; $session_time = 0; $inc = 0; $active_buffer = -1; $failures=0; while( ($failures<(strlen($sources)*2))
An Introduction to PHP3 error_reporting(0); if($fd = fopen("/tmp/counter","w")) { $buf = fwrite($fd,strval($current_counter )); fclose($fd); } error_reporting(E_ALL); $inc = 0; } } else if($suffix == "sequence") { if($current_counter > $counter_max) { $counter = 1; } $dest .= "_" .
An Introduction to PHP3 error_log("No such file: ".
An Introduction to PHP3 system($command); } ?> 4.2.5 Example 5 – Send Images via E-mail This script will send 4 (2 pre-alarm and 2 post-alarm) images as attachments in an e-mail. The parameters available are: $buffer_prefix = "CAM"; $sources = "1"; $image_format = "fullsize"; $pre = 2; $post = 2; $predelay = 1000; $postdelay = 1000; $smtp_server = "mail.somewhere.com"; $subject = "test"; $from = " someone@somewhere.com"; $reply = " someone@somewhere.com "; $cc = " someone@somewhere.
An Introduction to PHP3 The script itself: error_reporting(E_ALL); error_log("Stopping buffer(s)",0); for($c=0;$c<(strlen($sources));$c++) { // Stop the, by utask, //started buffers $command="bufferd -stop -buffername ".$buffer_prefix.substr($sources,$c,1); system($command); } for($c=0;$c<(strlen($sources));$c++) { // For each buffer specified $status_file = "/tmp/".$buffer_prefix.substr($sources,$c,1).
An Introduction to Shells in General 5 An Introduction to Shells in General A shell is a programming language that is fully equipped with: • variables • conditional and iterative constructs 5.1 The mish shell The commands available in mish are essentially the same as the ones commonly used in other shells on any Linux/Unix system, so the manual pages can often be useful. The difference is that the commands in mish have been simplified, i.e. options have been removed.
An Introduction to Shells in General • • • -v Echo input lines as they are read -x Trace -u Unset variables Example sh script #Run a shell script Description Sh is the shell, which forms the user’s main interface with the system. On startup, the shell reads /etc/pro-file and $HOME/.profile, if they exist, and executes any commands they contain.
An Introduction to Shells in General The shell uses the following variables for specific purposes: SHELL HOME PATH IFS PS1 PS2 the path of the current shell the default value for the cd(1) command the directories to be searched to find commands the internal field separators for command strings the primary shell prompt the secondary shell prompt There are various forms of substitution on the shell command line: ‘...‘ "..." ’...
An Introduction to Shells in General trap arg sigs trap umask [n] wait [n] trap signals sigs and run arg on receipt list trapped signals set the user file creation mask; show the current umask wait for process pid n; wait for all processes The shell also contains a programming language, which has the following operators and flow control statements: # = && || (...) for case esac while do done if in then else elif until fi Comment. The rest of the line is ignored. Assignment. Set a shell variable.
An Introduction to Shells in General 5.3.1 basename Syntax: basename FILE [SUFFIX] Strips directory path and suffixes from FILE. If specified, also removes any trailing SUFFIX. Example: $ basename /usr/local/bin/foo foo $ basename /usr/local/bin/ bin $ basename /foo/bar.txt .txt bar 5.3.2 cat Syntax: cat [FILE]... Concatenates FILE(s) and prints them to stdout. Example: $ cat /proc/uptime 110716.72 17.67 5.3.3 chroot Syntax: chroot NEWROOT [COMMAND...] Run COMMAND with root directory set to NEWROOT.
An Introduction to Shells in General 5.3.5 cut Syntax: cut [OPTION]... [FILE]... Prints selected fields from each input FILE to standard output. Options: -b -c -d -s -f -n LIST LIST CHAR N Output only bytes from LIST Output only characters from LIST Use CHAR instead of tab as the field delimiter Output only the lines containing delimiter Print only these fields Ignored Example: $ echo "Hello world" | cut -f 1 -d ' ' Hello $ echo "Hello world" | cut -f 2 -d ' ' world 5.3.6 date Syntax: date [OPTION]...
An Introduction to Shells in General 4+0 records out 5.3.8 df Syntax: df [-hmk] [filesystem ...] Print the filesystem space used and space available. Options: -h -m -k print sizes in human readable format (e.g.
An Introduction to Shells in General 16 12 104 2417 ./scripts ./docs/CVS ./docs . 5.3.11 echo Syntax: echo [-neE] [ARG ...] Prints the specified ARGs to stdout Options: -n -e -E suppress trailing newline interpret backslash-escaped characters (i.e. \t=tab etc) disable interpretation of backslash-escaped characters Example: $ echo "Erik is cool" Erik is cool $ echo -e "Erik is cool" Erik is cool $ echo "Erik is cool" Erik is cool 5.3.12 env Syntax: env [-] [-iu] [name=value ...
An Introduction to Shells in General ARG1 + ARG2 arithmetic ARG1 - ARG2 arithmetic ARG1 * ARG2 arithmetic ARG1 / ARG2 arithmetic ARG1 % ARG2 arithmetic STRING : REGEXP match STRING REGEXP substr STRING POS LENGTH index STRING CHARS length STRING quote TOKEN ( EXPRESSION ) sum of ARG1 and ARG2 difference of ARG1 and ARG2 product of ARG1 and ARG2 quotient of ARG1 divided by ARG2 remainder of ARG1 divided by ARG2 anchored pattern match of REGEXP in STRING same as STRING : REGEXP substring of STRING, POS cou
An Introduction to Shells in General -follow -name PATTERN -print -type X -perm PERMS Dereference symbolic links. File name (leading directories removed) matches PATTERN. Print (default and assumed). Filetype matches X (where X is one of: f,d,l,b,c,...) Permissions match any of (+NNN); all of (-NNN); or exactly (NNN) Modified time is greater than (+N); less than (-N); or exactly (N) days -mtime TIME Example: $ find / -name /etc/passwd /etc/passwd 5.3.17 grep Syntax: grep [-ihHnqvs] pattern [files...
An Introduction to Shells in General daemon:x:1:1:daemon:/usr/sbin:/bin/sh 5.3.20 hostname Syntax: hostname [OPTION] {hostname | -F file} Get or set the hostname or DNS domain name. If a hostname is given (or a file with the -F parameter), the host name will be set. Options: -s -i -d -F, --file FILE Short Addresses for the hostname DNS domain name Use the contents of FILE to specify the hostname Example: $ hostname slag 5.3.21 id Syntax: id [OPTIONS]...
An Introduction to Shells in General tty2::askfirst:/bin/sh tty3::askfirst:/bin/sh tty4::askfirst:/bin/sh If you choose to use an /etc/inittab file, the inittab entry format is as follows: ::: : WARNING! This field has a non-traditional meaning for BusyBox init! The id field is used by BusyBox init to specify the controlling tty for the specified process to run on. The contents of this field are appended to "/dev/" and used as-is.
An Introduction to Shells in General Unrecognized actions (like initdefault) will cause init to emit an error message, and then go along with its business. All actions are run in the reverse order from how they appear in /etc/inittab. : Specifies the process to be executed and it's command line. Example /etc/inittab file: # This is run first except when booting in single-user mode. # ::sysinit:/etc/init.
An Introduction to Shells in General 5.3.24 logger Syntax: logger [OPTION]... [MESSAGE] Write MESSAGE to the system log. If MESSAGE is omitted, log stdin. Options: -s -t -p Log to stderr as well as the system log. Log using the specified tag (defaults to user name). Enter the message with the specified priority. This may be numerical or a ``facility.level'' pair. Example: $ logger "hello" 5.3.25 logname Syntax: logname Print the name of the current user. Example: $ logname root 5.3.
An Introduction to Shells in General -u -v -w NUM -x -X -h -k with -l: show access time sort the listing by version assume the terminal is NUM columns wide list entries by lines instead of by columns sort the listing by extension print sizes in human readable format (e.g., 1K 243M 2G ) print sizes in kilobytes(default) 5.3.28 mkdir Syntax: mkdir [OPTION] DIRECTORY... Create the DIRECTORY(ies), if they do not already exist.
An Introduction to Shells in General 5.3.31 mount Syntax: mount [flags] device directory [-o options,more-options] Mount a filesystem. Flags: -a: -f: -n: -o option: -r: -t fs-type: -w: Mount all filesystems in fstab. "Fake" Add entry to mount table but don't mount it. Don't write a mount table entry. One of many filesystem options, listed below. Mount the filesystem read-only. Specify the filesystem type. Mount for reading and writing (default).
An Introduction to Shells in General 5.3.34 printf Syntax: printf FORMAT [ARGUMENT...] Formats and prints ARGUMENT(s) according to FORMAT, where FORMAT controls the output exactly as in C printf. Example: $ printf "Val=%d " 5 Val=5 5.3.35 pwd Syntax: pwd Print the full filename of the current working directory. Example: $ pwd /root 5.3.36 rdate Syntax: rdate [OPTION] HOST Get and possibly set the system date and time from a remote HOST. Options: -s -p Set the system date and time (default).
An Introduction to Shells in General 5.3.39 rmdir Syntax: rmdir [OPTION]... DIRECTORY... Remove the DIRECTORY(ies), if they are empty. Example: # rmdir /tmp/foo 5.3.40 sed Syntax: sed [-Vhnef] pattern [files...
An Introduction to Shells in General 5.3.43 stty Syntax: stty [-a|g] [-F device] [SETTING]... Without arguments, prints baud rate, line discipline, and deviations from stty sane. Options: -F device -a -g [SETTING] open device instead of stdin print all current settings in human-readable form print in stty-readable form see documentation 5.3.44 sync Syntax: sync Write all buffered filesystem blocks to disk. 5.3.45 tail Syntax: Tail [OPTION]... [FILE]...
An Introduction to Shells in General 5.3.47 test Syntax: test EXPRESSION or [ EXPRESSION ] Checks file types and compares values returning an exit code determined by the value of EXPRESSION. Example: $ $ 1 $ $ 0 $ $ 0 $ $ 1 test 1 -eq 2 echo $? test 1 -eq 1 echo $? [ -d /etc ] echo $? [ -d /junk ] echo $? 5.3.48 touch Syntax: touch [-c] file [file ...] Update the last-modified date on the given file[s].
An Introduction to Shells in General 5.3.50 true Syntax: true Return an exit code of TRUE (0). Example: $ true $ echo $? 0 5.3.51 tty Syntax: tty Print the file name of the terminal connected to standard input. Options: -s print nothing, only return an exit status Example: $ tty /dev/tty2 5.3.52 umount Syntax: umount [flags] filesystem|directory Unmount file systems.
An Introduction to Shells in General Linux debian 2.2.15pre13 #5 Tue Mar 14 16:03:50 MST 2000 i686 unknown 5.3.54 uniq Syntax: uniq [OPTION]... [INPUT [OUTPUT]] Discard all but one of successive identical lines from INPUT (or standard input), writing to OUTPUT (or standard output). Options: -c -d -u prefix lines by the number of occurrences only print duplicate lines only print unique lines Example: $ echo -e "a a b c c a" | sort | uniq a b c 5.3.55 usleep Syntax: usleep N Pause for N microseconds.
An Introduction to Shells in General 5.3.57 whoami Syntax: whoami Prints the user name associated with the current effective user id. 5.3.58 xargs Syntax: xargs [COMMAND] [ARGS...] Executes COMMAND on every item given by standard input. Example: $ ls | xargs gzip $ find . -name '*.c' -print | xargs rm 5.3.59 yes Syntax: yes [OPTION]... [STRING]... Repeatedly outputs a line with all specified STRING(s), or 'y'. 5.
An Introduction to Shells in General Brian Candler tiny-ls(ls) Randolph Chung fbset, ping, hostname, and mkfifo Dave Cinege more(v2), makedevs, dutmp, modularization, auto links file, various fixes, Linux Router Project maintenance Karl M. Hegbloom cp_mv.c, the test suite, various fixes to utility.c, &c. Daniel Jacobowitz mktemp.c Matt Kraai
An Introduction to Shells in General 5.5 Using Variables As is the case with almost any language, the use of variables is very important in shell programs. You can assign a value to a variable simply by typing the variable name followed by the equal sign (=) and the value you want to assign to the variable. For example, if you wanted to assign a value of 5 to the variable count, you would enter: count=5 Note that you do not have to declare the variable as you would if you were programming in C or Pascal.
An Introduction to Shells in General Variable Symbol $@ Description Contains the argument list. By itself, $@ is equivalent to $1, $2 and so on up to the number of arguments. The construct "$@" is equivalent to "$1", "$2" ...., which preserves the argument list. Without quotes, $@ divides arguments containing spaces into separate arguments. 5.7 The importance of Quotation Marks The use of the different types of quotation marks is very important in shell programming.
An Introduction to Shells in General The back quote marks (") perform a different function. They are used when you want to use the results of a command in another command. For example, if you wanted to set the value of the variable contents equal to the list of files in the current directory, you would type the following command: contents='ls' ´ 5.8 The test Command A command called test is used to evaluate conditional expressions.
An Introduction to Shells in General 5.8.3 File operators Variable Symbol -d -f -r -s -z -x -e filename filename filename filename filename filename filename Description Returns True if filename is a directory. Returns True if filename is an ordinary file. Returns True if the process can read filename. Returns True if filename has a non-zero length. Returns True if the process can write filename. Returns True if filename is executable. Returns True if filename exists. 5.8.
An Introduction to Shells in General The case statement The case statement enables you to compare a pattern with several other patterns and execute a block of code if a match is found. The syntax of the case statement is: case string in str1) commands;; str2) commands;; *) commands;; esac string is compared to str1 and str2. If one of these strings matches string1, the commands up until the double semicolon (;;) are executed.
An Introduction to Shells in General while [ expression ]; do statements done The until statement The until statement is very similar in syntax and function to the while statement. The only real difference between the two is that the until statement executes its code block while its conditional expression is false, and the while statement executes its code block while its conditional expression is true.
Shell Script Examples 6 Shell Script Examples The following pages contain complete shell scripts, which are customized for the most common applications. Shell Scripting Tips • Include #!/bin/mish –x to debug your scripts. Run via Telnet. • A very useful program for fetching or uploading scripts to the product, Ultra Edit, can be downloaded from http://www.ultraedit.com/ 6.1 The configuration file The configuration file is located in the /etc/applications directory.
Shell Script Examples seq_sources="1" # The format of the images specified to be taken according to the HTTP# API for the sequential images seq_image_format="fullsize" # The type of the suffix to use on the uploaded files.
Shell Script Examples 6.2 Script examples The script examples that follow are located in the ROM file system of the Axis camera/video server. The scripts are, in their default implementations, “configured” by the Application Wizard, which is available from the product’s configuration pages. The scripts are shown here as they actually are, and the configuration options described won’t actually change the scripts themselves.
Shell Script Examples The script itself continues: #!/bin/mish PATH=/bin:/sbin:/usr/bin:/usr/sbin # Read the config file . /etc/applications/config_$1 # Read the optional config file if [ -e /etc/applications/pre_config_$1 ]; then . /etc/applications/pre_config_$1 fi # Stop the, by utask, started buffers bufferd -stop -buffername $2 # Path of the status file status_file="/tmp/$2/status" # Wait until bufferd is ready with the images, i.e.
Shell Script Examples # previous started one) date(w(01,2,3,4,5,6)) pattern ((IO0:/)) immune once % /etc/scripts/alarm_ftp_net : CAM1 IO0; 6.2.2 Example 2 – Upload via FTP and E-mail This script will upload 2 pre-alarm and 2 post-alarm images via FTP and also send an e-mail as notification of the event.
Shell Script Examples #!/bin/mish PATH=/bin:/sbin:/usr/bin:/usr/sbin # Read the config file . /etc/applications/config_$1 # Read the optional config file if [ -e /etc/applications/pre_config_$1 ]; then .
Shell Script Examples 6.2.3 Example 3 – Sequential Upload via FTP When input 0 goes high, this script will, for 10 seconds, upload images via FTP, at 2 second intervals. The uploaded images can be named by specifying a suffix. These can be date, incremental sequence number or limited sequence (overwrites files when maximum is reached).
Shell Script Examples # Start the buffers as specified by the parameters bufferd -start -buffername $2 -snapshot -pre 1 -predelay "$delay" -uri ftp://jpg/"$sources"/"$image_format".jpg -format snapshot_%y%m%d_%H%M%S.
Shell Script Examples current_counter="00$current_counter" echo $current_counter > /tmp/counter else if [ $current_counter -lt 100 ]; then current_counter="0$current_counter" echo $current_counter > /tmp/counter fi fi fi # If the uploaded file must be sequenced for an index # limited by the value of the variable $counter_max if [ $suffix = sequenced ]; then # If the limit is reached restart current counter at 1 if [ $current_counter -gt $counter_max ]; then current_counter=001 fi # Modify the path of the n
Shell Script Examples 6.2.3.1 Task.list This is the task.list. used to run the script above. # If a positive transition is detected on the IO port 0, execute the # script for the first camera and the buffer named SNAP1 date(w(0,1,2,3,4,5,6)) pattern ((IO0:/)) immune once % /etc/scripts/seq_ftp_net : CAM1 SNAP1; 6.2.4 Example 4 – Upload Images via E-mail This script will send 4 (2 pre-alarm and 2 post-alarm) images as attachments in an e-mail.
Shell Script Examples The script itself: #!/bin/mish PATH=/bin:/sbin:/usr/bin:/usr/sbin # Read the config file . /etc/applications/config_$1 # Read the optional config file if [ -e /etc/applications/pre_config_$1 ]; then . /etc/applications/pre_config_$1 fi # Stop the, by utask, started buffers bufferd -stop -buffername $2 # Path of the status file status_file="/tmp/$2/status" # Wait until bufferd is ready with the images, i.e.
Shell Script Examples 1000 -postdelay 1000 -uri ftp://jpg/1/352x288.jpg; # If a positive transition is detected on the IO port 0, execute the # script for the first camera and the buffer named IO0 (the same as the # previous started one) date(w(0,1,2,3,4,5,6)) pattern ((IO0:/)) immune once % /etc/scripts/alarm_smtp_net : CAM1 IO0; 6.2.5 Example 5 – Sequential Upload with Notification via E-mail This script will upload sequential images specified via FTP.
Shell Script Examples # The path to append to sequential uploads. This path must exist on the # server prior to upload seq_destination="upload/sequential" # --- SMTP parameters --# The server to use as mail server smtp_server="mail.somewhere.com" # The subject to use in the mail subject="'Alarm'" # The specified sender from="someone@somewhere.com" # The specified receiver of reply reply="someone@somewhere.com" # The specified receiver of a copy of this mail cc="someone@somewhere.
Shell Script Examples while [ ! -f $status_file ]; do sleep $tmp done rm $status_file # FTP connection if [ x$passive_mode = xyes ]; then sftpclient -L -s -m $ftp_server -n $port -c $destination -k /tmp/$2 -u $user -w $pass else sftpclient -L -m $ftp_server -n $port -c $destination -k /tmp/$2 – u $user -w $pass fi if [ $? -eq 1 ]; then logger -t $0[$$] FTP failed! fi # Reset and restart buffer for alarm images bufferd -reset -buffername $2 bufferd -start -buffername $2 -pre "$pre" -post "$post" -predelay "
Shell Script Examples OK=1 # The image has been found # Path of the image source_file=$source_file"/"$tmp fi fi done # FTP connection if [ x$passive_mode = xyes ]; then # Passive mode sftpclient -L -s -m $ftp_server -n $port -c $seq_destination -k /tmp/$3 -u $user -w $pass else # Non passive mode sftpclient -L -m $ftp_server -n $port -c $seq_destination -k /tmp/$3 -u $user -w $pass fi if [ $? -eq 1 ]; then # If an error appeared logger -t $0[$$] FTP failed! # Log this error exit=1 # Exit the script else rm
Troubleshooting 7 Troubleshooting 7.1 Script related problems Axis Communications AB does not provide support for application development of any kind. The information here is provided "as is", and there is no guarantee that any of the examples shown will work in your particular application. 7.2 Product related problems If you run into problems, please try these steps first, before contacting your local supplier: 1. Consult the Troubleshooting section of the product’s Users Guide. 2.