NuttShell (NSH)Last Updated: June 13, 2017 |
Table of Contents |
The NSH Library.
The
NSH Consoles. Using settings in the configuration file, NSH may be configured to use (1) the serial stdin/out, (2) a USB serial device (such as CDC/ACM), or (3) a telnet connection as the console. Or, perhaps even all at once since or BOTH. An indefinite number of telnet sessions are supported. Start-Up prompt. When NSH is started, you will see the a welcome message such the following on the selected console: NuttShell (NSH) nsh>The greeting may also include NuttX versioning information if you are using a versioned copy of NuttX. nsh> is the NSH prompt and indicates that you may enter a command from the console.
USB console startup. When using a USB console, the start-up sequence differs a little: In this case, you are required to press ENTER three times. Then NSH prompt will appear as described above. This is required for the following reasons:
Extended Command Line Editing.
By default, NuttX uses a simple command line editor that allows command entry after the
Simple, Re-directed, and Background Commands. The NuttShell (NSH) is a simple shell application. NSH supports the following commands forms:
Where:
[nice [-d <niceness>>]] <cmd> [> <file>|>> <file>] [&]
Where Multiple commands per line. NSH will accept multiple commands per command line with each command separated with the semi-colon character (;). Optional Syntax Extensions Because these features commit significant resources, they are disabled by default.
Will execute the program named CONFIG_NSH_ARGCAT .
Support concatenation of strings with environment variables or command output. For example:
set FOO XYZ set BAR 123 set FOOBAR ABC_${FOO}_${BAR}would set the environment variable FOO to XYZ , BAR to 123 and FOOBAR to ABC_XYZ_123 .
If CONFIG_NSH_ARGCAT is not selected, then a slightly smaller FLASH footprint results but then also only simple environment variables like $FOO can be used on the command line.
An if <cmd> then [sequence of <cmd>] else [sequence of <cmd>] fi
Looping Constructs.
until <cmd> do [sequence of <cmd>] done The
Environment Variables:
NSH Start-Up Script.
NSH supports options to provide a start up script for NSH. In general
this capability is enabled with
Default Start-Up Behavior. The implementation that is provided is intended to provide great flexibility for the use of Start-Up files. This paragraph will discuss the general behavior when all of the configuration options are set to the default values.
In this default case, enabling
/etc , resulting in:
|--dev/ | `-- ram0 `--etc/ `--init.d/ `-- rcS # Create a RAMDISK and mount it at XXXRDMOUNTPOINTXXX mkrd -m 1 -s 512 1024 mkfatfs /dev/ram1 mount -t vfat /dev/ram1 /tmp /etc/init.d/rcS at start-up (before the
first NSH prompt. After execution of the script, the root FS will look
like:
|--dev/ | |-- ram0 | `-- ram1 |--etc/ | `--init.d/ | `-- rcS `--tmp/
Modifying the ROMFS Image.
The contents of the
NOTE:
All of the startup-behavior is contained in Further Information. See the section on Customizing the NuttShell for additional, more detailed information about the NSH start-up script and how to modify it.
Command Syntax: [ <expression> ] test <expression>
Synopsis.
These are two alternative forms of the same command. They support
evaluation of a boolean expression which sets Expression Syntax: expression = simple-expression | !expression | expression -o expression | expression -a expression simple-expression = unary-expression | binary-expression unary-expression = string-unary | file-unary string-unary = -n string | -z string file-unary = -b file | -c file | -d file | -e file | -f file | -r file | -s file | -w file binary-expression = string-binary | numeric-binary string-binary = string = string | string == string | string != string numeric-binary = integer -eq integer | integer -ge integer | integer -gt integer | integer -le integer | integer -lt integer | integer -ne integer
Command Syntax: addroute <target> <netmask> <router> Synopsis. This command adds an entry in the routing table. The new entry will map the IP address of a router on a local network (<router>) to an external network characterized by the <target> IP address and a network mask <netmask> Example: nsh> addroute 1.1.1.1 2.2.2.2 3.3.3.3
Command Syntax: arp [-a <ipaddr> |-d <ipaddr> |-s <ipaddr> <hwaddr>] Synopsis. Access the OS ARP table.
Example: nsh> arp -a 10.0.0.1 nsh: arp: no such ARP entry: 10.0.0.1 nsh> arp -s 10.0.0.1 00:13:3b:12:73:e6 nsh> arp -a 10.0.0.1 HWAddr: 00:13:3b:12:73:e6 nsh> arp -d 10.0.0.1 nsh> arp -a 10.0.0.1 nsh: arp: no such ARP entry: 10.0.0.1
Command Syntax: base64dec [-w] [-f] <string or filepath> Synopsis. To be provided.
Command Syntax: base64enc [-w] [-f] <string or filepath> Synopsis. To be provided.
Command Syntax: basename <path> [<suffix>]
Synopsis.
Extract the final string from a
Command Syntax: break
Synopsis.
The
Command Syntax: cat
Synopsis.
This command copies and concatenates all of the files at
Command Syntax: cd [<dir-path>|-|~|..]
Synopsis.
Changes the current working directory (
Forms:
Command Syntax: cmp <path1> <path2>
Synopsis.
Compare of the contents of the file at
Command Syntax: cp <source-path> <dest-path>
Synopsis.
Copy of the contents of the file at
Command Syntax: date [-s "MMM DD HH:MM:SS YYYY"] Synopsis. Show or set the current date and time.
Only one format is used both on display and when setting the date/time:
data -s "Sep 1 11:30:00 2011" 24-hour time is used.
Command Syntax: dd if=<infile> of=<outfile> [bs=<sectsize>] [count=<sectors>] [skip=<sectors>] Synopsis. Copy blocks from <infile> to <outfile>. <infile> or <outfile> may be the path to a standard file, a character device, or a block device. Examples follow:
nsh> ls -l /dev /dev: brw-rw-rw- 0 ram0 crw-rw-rw- 0 zero nsh> dd if=/dev/zero of=/dev/ram0 nsh> ls -l /dev /dev: crw-rw-rw- 0 null brw-rw-rw- 0 ram0 nsh> dd if=/dev/ram0 of=/dev/null
Command Syntax: delroute <target> <netmask> Synopsis. The entry removed will be the first entry in the routing table that matches the external network characterized by the <target> IP address and the network mask <netmask> Example: nsh> delroute 1.1.1.1 2.2.2.2
Command Syntax: df [-h] Synopsis. Show the state of each mounted volume. As an example: nsh> mount /etc type romfs /tmp type vfat nsh> df Block Number Size Blocks Used Available Mounted on 64 6 6 0 /etc 512 985 2 983 /tmp nsh>
If
Command Syntax: dirname <path>
Synopsis.
Extract the path string leading up to the full
Command Syntax: echo [<string|$name> [<string|$name>...]] Synopsis. Copy the sequence of strings and expanded environment variables to console output (or to a file if the output is re-directed).
Command Syntax: exec <hex-address>
Synopsis.
Execute the user logic at address
Command Syntax: exit
Synopsis.
Exit NSH. Only useful for the serial front end if you have started some other tasks (perhaps
using the
Command Syntax: free Synopsis. Show the current state of the memory allocator. For example, nsh> free total used free largest Mem: 4194288 1591552 2602736 2601584 nsh> Where:
Command Syntax: get [-b|-n] [-f <local-path>] -h <ip-address> <remote-path>
Synopsis.
Copy the file at Other options:
Command Syntax: help [-v] [<cmd>] Synopsis. Presents summary information about NSH commands to console. Options:
Command Syntax: hexdump <file or device> [skip=<bytes>] [count=<bytes>] Synopsis. Dump data in hexadecimal format from a file or character device.
The
Command Syntax: ifconfig [nic_name [<ip-address>|dhcp]] [dr|gw|gateway <dr-address>] [netmask <net-mask>] [dns <dns-address>] [hw <hw-mac>]]
Synopsis.
Multiple forms of the
NOTE: This commands depends upon having the procfs file system configured into the system. The procfs file system must also have been mounted with a command like: nsh> mount -t procfs /proc
Command Syntax: ifdown <nic-name> Synopsis. Take down the interface identified by the name <nic-name>. Example: ifdown eth0
Command Syntax: ifup <nic-name> Synopsis. Bring up down the interface identified by the name <nic-name>. Example: ifup eth0
Command Syntax: insmod <file-path> <module-name> Synopsis. Install the loadable OS module at <file-path> as module <module-name>. Example: nsh> ls -l /mnt/romfs /mnt/romfs: dr-xr-xr-x 0 . -r-xr-xr-x 9153 chardev nsh> ls -l /dev /dev: crw-rw-rw- 0 console crw-rw-rw- 0 null brw-rw-rw- 0 ram0 crw-rw-rw- 0 ttyS0 nsh> lsmod NAME INIT UNINIT ARG TEXT SIZE DATA SIZE nsh> insmod /mnt/romfs/chardev mydriver nsh> ls -l /dev /dev: crw-rw-rw- 0 chardev crw-rw-rw- 0 console crw-rw-rw- 0 null brw-rw-rw- 0 ram0 crw-rw-rw- 0 ttyS0 nsh> lsmod NAME INIT UNINIT ARG TEXT SIZE DATA SIZE mydriver 20404659 20404625 0 20404580 552 204047a8 0
Command Syntax: kill -<signal> <pid> Synopsis. Send the <signal> to the task identified by <pid>. Example: nsh> mkfifo /dev/fifo nsh> cat /dev/fifo & cat [2:128] nsh> ps PID PRI POLICY TYPE NPX STATE EVENT SIGMASK COMMAND 0 0 FIFO Kthread --- Ready 00000000 Idle Task 1 128 RR Task --- Running 00000000 init 2 128 FIFO pthread --- Waiting Semaphore 00000000 <pthread>(51ea50) nsh> kill -9 2 nsh> ps PID PRI POLICY TYPE NPX STATE EVENT SIGMASK COMMAND 0 0 FIFO Kthread --- Ready 00000000 Idle Task 1 128 RR Task --- Running 00000000 init nsh>
NOTE:
NuttX does not support a FULL POSIX signalling system.
Standard signals like SIGCHLD, SIGINTR, SIGKILL, etc. do not exist in NuttX and sending those signals may not have the result that you expect.
Rather, NuttX supports only what are referred to as POSIX real-time signals.
These signals may be used to communicate with running tasks, may be use to waiting waiting tasks, etc.
But, as an example,
Command Syntax 1: losetup [-o <offset>] [-r] <dev-path> <file-path>
Synopsis.
Setup the loop device at <dev-path> to access the file at <file-path> as a block device.
In the following example a 256K file is created ( nsh> dd if=/dev/zero of=/tmp/image bs=512 count=512 nsh> ls -l /tmp /tmp: -rw-rw-rw- 262144 IMAGE nsh> losetup /dev/loop0 /tmp/image nsh> ls -l /dev /dev: brw-rw-rw- 0 loop0 nsh> mkfatfs /dev/loop0 nsh> mount -t vfat /dev/loop0 /mnt/example nsh> ls -l /mnt ls -l /mnt /mnt: drw-rw-rw- 0 example/ nsh> echo "This is a test" >/mnt/example/atest.txt nsh> ls -l /mnt/example /mnt/example: -rw-rw-rw- 16 ATEST.TXT nsh> cat /mnt/example/atest.txt This is a test nsh> Command Syntax 2: losetup d <dev-path> Synopsis. Teardown the setup for the loop device at <dev-path>.
Command Syntax: ln [-s] <target> <link>
Synopsis.
The
Command Syntax: ls [-lRs] <dir-path>
Synopsis.
Show the contents of the directory at Options:
Command Syntax: lsmod Synopsis. Show information about the currently installed OS modules. This information includes:
Example: nsh> lsmod NAME INIT UNINIT ARG TEXT SIZE DATA SIZE mydriver 20404659 20404625 0 20404580 552 204047a8 0
Command Syntax: md5 [-f] <string or filepath> Synopsis. To be provided.
Command Syntax: mb <hex-address>[=<hex-value>][ <hex-byte-count>] mh <hex-address>[=<hex-value>][ <hex-byte-count>] mw <hex-address>[=<hex-value>][ <hex-byte-count>] Synopsis. Access memory using byte size access (mb), 16-bit accesses (mh), or 32-bit access (mw). In each case,
Example:
nsh> mh 0 16 0 = 0x0c1e 2 = 0x0100 4 = 0x0c1e 6 = 0x0110 8 = 0x0c1e a = 0x0120 c = 0x0c1e e = 0x0130 10 = 0x0c1e 12 = 0x0140 14 = 0x0c1e nsh>
Command Syntax: ps Synopsis. Show the currently active threads and tasks. For example, nsh> ps PID PRI POLICY TYPE NPX STATE EVENT SIGMASK COMMAND 0 0 FIFO Kthread --- Ready 00000000 Idle Task 1 128 RR Task --- Running 00000000 init 2 128 FIFO Task --- Waiting Semaphore 00000000 nsh_telnetmain() 3 100 RR pthread --- Waiting Semaphore 00000000 <pthread>(21) nsh> NOTE: This commands depends upon having the procfs file system configured into the system. The procfs file system must also have been mounted with a command like: nsh> mount -t procfs /proc
Command Syntax: mkdir <path>
Synopsis.
Create the directory at
Limited to Mounted File Systems.
Recall that NuttX uses a pseudo file system for its root file
system.
The Example: nsh> mkdir /mnt/fs/tmp nsh> ls -l /mnt/fs /mnt/fs: drw-rw-rw- 0 TESTDIR/ drw-rw-rw- 0 TMP/ nsh>
Command Syntax: mkfatfs [-F <fatsize>] <block-driver>
Synopsis.
Format a fat file system on the block device specified by
NSH provides this command to access the
Command Syntax: mkfifo <path>
Synopsis.
Creates a FIFO character device anywhere in the pseudo file system, creating
whatever pseudo directories that may be needed to complete the Example nsh> ls -l /dev /dev: crw-rw-rw- 0 console crw-rw-rw- 0 null brw-rw-rw- 0 ram0 nsh> mkfifo /dev/fifo nsh> ls -l /dev ls -l /dev /dev: crw-rw-rw- 0 console crw-rw-rw- 0 fifo crw-rw-rw- 0 null brw-rw-rw- 0 ram0 nsh>
Command Syntax: mkrd [-m <minor>] [-s <sector-size>] <nsectors>
Synopsis.
Create a ramdisk consisting of Example nsh> ls /dev /dev: console null ttyS0 ttyS1 nsh> mkrd 1024 nsh> ls /dev /dev: console null ram0 ttyS0 ttyS1 nsh>
Once the ramdisk has been created, it may be formatted using
the Example nsh> mkrd 1024 nsh> mkfatfs /dev/ram0 nsh> mount -t vfat /dev/ram0 /tmp nsh> ls /tmp /tmp: nsh>
Command Syntax:
mount -t <fstype> [-o <options>] <block-device>
Synopsis.
The
If the mount parameters are provided on the command after the
After the volume has been mounted in the NuttX pseudo file system, it may be access in the same way as other objects in the file system. Examples: Using nsh> ls -l /dev /dev: crw-rw-rw- 0 console crw-rw-rw- 0 null brw-rw-rw- 0 ram0 nsh> ls /mnt nsh: ls: no such directory: /mnt nsh> mount -t vfat /dev/ram0 /mnt/fs nsh> ls -l /mnt/fs/testdir /mnt/fs/testdir: -rw-rw-rw- 15 TESTFILE.TXT nsh> echo "This is a test" >/mnt/fs/testdir/example.txt nsh> ls -l /mnt/fs/testdir /mnt/fs/testdir: -rw-rw-rw- 15 TESTFILE.TXT -rw-rw-rw- 16 EXAMPLE.TXT nsh> cat /mnt/fs/testdir/example.txt This is a test nsh> Using nsh> mount /etc type romfs /mnt/fs type vfat /tmp type vfat
Command Syntax: mv <old-path> <new-path>
Synopsis.
Rename the file object at
Command Syntax: nfsmount <server-address> <mount-point> <remote-path> Synopsis. Mount the remote NFS server directory<remote-path> at <mount-point> on the target machine. <server-address> is the IP address of the remote server.
Command Syntax: nslookup <host-name>
Synopsis.
Lookup and print the IP address associated with
Command Syntax: passwd <username> <password> Synopsis. Set the password for the existing user <username> to <password>.
Command Syntax: ping [-c <count>] [-i <interval>] <ip-address> ping6 [-c <count>] [-i <interval>] <ip-address> Synopsis. Test the network communication with a remote peer. Example, nsh> ping 10.0.0.1 PING 10.0.0.1 56 bytes of data 56 bytes from 10.0.0.1: icmp_seq=1 time=0 ms 56 bytes from 10.0.0.1: icmp_seq=2 time=0 ms 56 bytes from 10.0.0.1: icmp_seq=3 time=0 ms 56 bytes from 10.0.0.1: icmp_seq=4 time=0 ms 56 bytes from 10.0.0.1: icmp_seq=5 time=0 ms 56 bytes from 10.0.0.1: icmp_seq=6 time=0 ms 56 bytes from 10.0.0.1: icmp_seq=7 time=0 ms 56 bytes from 10.0.0.1: icmp_seq=8 time=0 ms 56 bytes from 10.0.0.1: icmp_seq=9 time=0 ms 56 bytes from 10.0.0.1: icmp_seq=10 time=0 ms 10 packets transmitted, 10 received, 0% packet loss, time 10190 ms nsh>
Command Syntax: poweroff Synopsis. Shutdown and power off the system immediately. This command depends on hardware support to power down the system.
NOTE: Supporting both the
Command Syntax: put [-b|-n] [-f <remote-path>] -h <ip-address> <local-path>
Synopsis.
Copy the file at Other options:
Command Syntax: pwd Synopsis. Show the current working directory. nsh> cd /dev nsh> pwd /dev nsh> nsh> echo $PWD /dev nsh>
Command Syntax: readlink <link>
Synopsis.
Show the target of the soft link at the path
Command Syntax: reboot Synopsis. Reset and reboot the system immediately. This command depends on hardware support to reset the system.
NOTE: Supporting both the
Command Syntax: rm <file-path>
Synopsis.
Remove the specified Example: nsh> ls /mnt/fs/testdir /mnt/fs/testdir: TESTFILE.TXT EXAMPLE.TXT nsh> rm /mnt/fs/testdir/example.txt nsh> ls /mnt/fs/testdir /mnt/fs/testdir: TESTFILE.TXT nsh>
Command Syntax: rmdir <dir-path>
Synopsis.
Remove the specified Example: nsh> mkdir /mnt/fs/tmp nsh> ls -l /mnt/fs /mnt/fs: drw-rw-rw- 0 TESTDIR/ drw-rw-rw- 0 TMP/ nsh> rmdir /mnt/fs/tmp nsh> ls -l /mnt/fs /mnt/fs: drw-rw-rw- 0 TESTDIR/ nsh>
Command Syntax: rmmod <module-name> Synopsis. Remove the loadable OS module with the <module-name>. NOTE: An OS module can only be removed if it is not busy. Example: nsh> lsmod NAME INIT UNINIT ARG TEXT SIZE DATA SIZE mydriver 20404659 20404625 0 20404580 552 204047a8 0 nsh> rmmod mydriver nsh> lsmod NAME INIT UNINIT ARG TEXT SIZE DATA SIZE nsh>
Command Syntax: set [{+|-}{e|x|xe|ex}] [<name> <value>]
Synopsis.
Set the environment variable nsh> echo $foobar nsh> set foobar foovalue nsh> echo $foobar foovalue nsh> Set the 'exit on error control' and/or 'print a trace' of commands when parsing scripts in NSH. The settings are in effect from the point of execution, until they are changed again, or in the case of the init script, the settings are returned to the default settings when it exits. Included child scripts will run with the parents settings and changes made in the child script will effect the parent on return. Use 'set -e' to enable and 'set +e' to disable (ignore) the exit condition on commands. The default is -e. Errors cause script to exit. Use 'set -x' to enable and 'set +x' to disable (silence) printing a trace of the script commands as they are executed. The default is +x: no printing of a trace of script commands as they are executed. Example 1 - no exit on command not foundset +e notacommandExample 2 - will exit on command not found set -e notacommandExample 3 - will exit on command not found, and print a trace of the script commands set -exExample 4 - will exit on command not found, and print a trace of the script commands and set foobar to foovalue. set -ex foobar foovalue nsh> echo $foobar foovalue
Command Syntax: sh <script-path>
Synopsis.
Execute the sequence of NSH commands in the file referred
to by
Command Syntax: shutdown [--reboot] Synopsis. Shutdown and power off the system or, optionally, reset and reboot the system immediately. This command depends on hardware support to power down or reset the system; one, both, or neither behavior may be supported.
NOTE: The
Command Syntax: sleep <sec>
Synopsis.
Pause execution (sleep) for
Command Syntax: time "<command>" Synopsis. Perform command timing. This command will execute the following <command> string and then show how much time was required to execute the command. Time is shown with a resolution of 100 microseconds which may be beyond the resolution of many configurations. Note that the <command> must be enclosed in quotation marks if it contains spaces or other delimiters. Example: nsh> time "sleep 2" 2.0100 sec nsh> The additional 10 milliseconds in this example is due to the way that the sleep command works: It always waits one system clock tick longer than requested and this test setup used a 10 millisecond periodic system timer. Sources of error could include various quantization errors, competing CPU usage, and the additional overhead of the time command execution itself which is included in the total. The reported time is the elapsed time from starting of the command to completion of the command. This elapsed time may not necessarily be just the processing time for the command. It may included interrupt level processing, for example. In a busy system, command processing could be delayed if pre-empted by other, higher priority threads competing for CPU time. So the reported time includes all CPU processing from the start of the command to its finish possibly including unrelated processing time during that interval. Notice that: nsh> time "sleep 2 &" sleep [3:100] 0.0000 sec nsh> Since the sleep command is executed in background, the sleep command completes almost immediately. As opposed to the following where the time command is run in background with the sleep command: nsh> time "sleep 2" & time [3:100] nsh> 2.0100 sec
Command Syntax: umount <dir-path>
Synopsis.
Un-mount the file system at mount point Example: nsh> ls /mnt/fs /mnt/fs: TESTDIR/ nsh> umount /mnt/fs nsh> ls /mnt/fs /mnt/fs: nsh: ls: no such directory: /mnt/fs nsh>
Command Syntax: uname [-a | -imnoprsv] Synopsis. Print certain system information. With no options, the output is the same as -s.
Command Syntax: unset <name>
Synopsis.
Remove the value associated with the environment variable
nsh> echo $foobar foovalue nsh> unset foobar nsh> echo $foobar nsh>
Command Syntax: urldecode [-f] <string or filepath> Synopsis. To be provided.
Command Syntax: urlencode [-f] <string or filepath> Synopsis. To be provided.
Command Syntax: useradd <username> <password> Synopsis. Add a new user with <username> and <password>.
Command Syntax: userdel <username> Synopsis. Delete the user with the name <username>.
Command Syntax: usleep <usec>
Synopsis.
Pause execution (sleep) of
Command Syntax: wget [-o <local-path>] <url>
Synopsis.
Use HTTP to copy the file at Options:
Command Syntax: xd <hex-address> <byte-count>
Synopsis.
Dump Example: nsh> xd 410e0 512 Hex dump: 0000: 00 00 00 00 9c 9d 03 00 00 00 00 01 11 01 10 06 ................ 0010: 12 01 11 01 25 08 13 0b 03 08 1b 08 00 00 02 24 ....%..........$ ... 01f0: 08 3a 0b 3b 0b 49 13 00 00 04 13 01 01 13 03 08 .:.;.I.......... nsh>
The availability of the above commands depends upon features that may or may not be enabled in the NuttX configuration file. The following table indicates the dependency of each command on NuttX configuration settings. General configuration settings are discussed in the NuttX Porting Guide. Configuration settings specific to NSH as discussed at the bottom of this document. Note that in addition to general NuttX configuration settings, each NSH command can be individually disabled via the settings in the rightmost column. All of these settings make the configuration of NSH potentially complex but also allow it to squeeze into very small memory footprints.
Table. Command Dependencies on Configuration Settings
1
Because of hardware padding, the actual required packet size may be larger
The behavior of NSH can be modified with the following settings in
the
If Telnet is selected for the NSH console, then we must configure the resources used by the Telnet daemon and by the Telnet clients.
One or both of
If you use DHCPC, then some special configuration network options are required. These include:
If
When the default
Overview. The NuttShell (NSH) is a simple shell application that may be used with NuttX. It supports a variety of commands and is (very) loosely based on the bash shell and the common utilities used in Unix shell programming. The paragraphs in this appendix will focus on customizing NSH: Adding new commands, changing the initialization sequence, etc.
Overview.
NSH is implemented as a library that can be found at 4.1.1 NSH Initialization sequence
The NSH start-up sequence is very simple.
As an example, the code at
4.1.2
|
4.2 NSH Commands |
Overview. NSH supports a variety of commands as part of the NSH program. All of the NSH commands are listed in the NSH documentation above. Not all of these commands may be available at any time, however. Many commands depend upon certain NuttX configuration options. You can enter the help command at the NSH prompt to see the commands actual available:
nsh> help
For example, if network support is disabled, then all network-related commands will be missing from the list of commands presented by 'nsh> help
'.
You can see the specific command dependencies in the table above.
New commands can be added to the NSH very easily. You simply need to add two things:
The implementation of your command, and
A new entry in the NSH command table
Implementation of Your Command.
For example, if you want to add a new a new command called mycmd
to NSH, you would first implement the mycmd
code in a function with this prototype:
The argc
and argv
are used to pass command line arguments to the NSH command.
Command line parameters are passed in a very standard way: argv[0]
will be the name of the command, and argv[1]
through argv[argc-1]
are the additional arguments provided on the NSH command line.
The first parameter, vtbl
, is special.
This is a pointer to session-specific state information.
You don't need to know the contents of the state information, but you do need to pass this vtbl
argument when you interact with the NSH logic.
The only use you will need to make of the vtbl
argument will be for outputting data to the console.
You don't use printf()
within NSH commands.
Instead you would use:
void nsh_output(FAR struct nsh_vtbl_s *vtbl, const char *fmt, …);
So if you only wanted to output "Hello, World!" on the console, then your whole command implementation might be:
int cmd_mycmd(FAR struct nsh_vtbl_s *vtbl, int argc, char **argv) { nsh_output(vtbl, "e;Hello, World!"e;); return 0; }
The prototype for the new command should be placed in apps/examples/nshlib/nsh.h>
.
Adding You Command to the NSH Command Table. All of the commands support by NSH appear in a single table called:
const struct cmdmap_s g_cmdmap[]
That table can be found in the file apps/examples/nshlib/nsh_parse.c
.
The structure cmdmap_s
is also defined in apps/nshlib/nsh_parse.c
:
struct cmdmap_s { const char *cmd; /* Name of the command */ cmd_t handler; /* Function that handles the command */ uint8_t minargs; /* Minimum number of arguments (including command) */ uint8_t maxargs; /* Maximum number of arguments (including command) */ const char *usage; /* Usage instructions for 'help' command */ };
This structure provides everything that you need to describe your command:
Its name (cmd
), the function that handles the command (cmd_mycmd()
), the minimum and maximum number of arguments needed by the command,
and a string describing the command line arguments.
That last string is what is printed when enter "nsh> help
".
So, for you sample command, you would add the following the to the g_cmdmap[]
table:
{ "mycmd", cmd_mycmd, 1, 1, NULL },
This entry is particularly simply because mycmd
is so simple.
Look at the other commands in g_cmdmap[]
for more complex examples.
4.3 NSH "Built-In" Applications |
Overview. In addition to these commands that are a part of NSH, external programs can also be executed as NSH commands. These external programs are called "Built-In" Applications for historic reasons. That terminology is somewhat confusing because the actual NSH commands as described above are truly "built-into" NSH whereas these applications are really external to NuttX.
These applications are built-into NSH in the sense that they can be executed by simply typing the name of the application at the NSH prompt. Built-in application support is enabled with these configuration option:
CONFIG_BUILTIN
:
Enable NuttX support for builtin applications.
CONFIG_NSH_BUILTIN_APPS
:
Enable NSH support for builtin applications.
When these configuration options are set, you will also be able to see the built-in applications if you enter "nsh> help". They will appear at the bottom of the list of NSH commands under:
Builtin Apps:
Note that no detailed help information beyond the name of the built-in application is provided.
Overview.
The underlying logic that supports the NSH built-in applications is called "Built-In Applications".
The builtin application logic can be found at apps/builtin
.
This logic simply does the following:
It supports registration mechanism so that builtin applications can dynamically register themselves at build time, and
Utility functions to look up, list, and execute the builtin applications.
Built-In Application Utility Functions.
The utility functions exported by the builtin application logic are prototyped in nuttx/include/nuttx/binfmt/builtin.h
and apps/include/builtin.h
.
These utility functions include:
int builtin_isavail(FAR const char *appname);
Checks for availability of application registered as appname
during build time.
const char *builtin_getname(int index);
Returns a pointer to a name of built-in application pointed by the index
.
This is the utility function that is used by NSH in order to list the available built-in applications when "nsh> help
" is entered.
int exec_builtin(FAR const char *appname, FAR const char **argv);
Executes built-in builtin application registered during compile time.
This is the utility function used by NSH to execute the built-in application.
Autogenerated Header Files. Application entry points with their requirements are gathered together in two files when NuttX is first built:
apps/builtin/builtin_proto.h
:
Prototypes of application task entry points.
apps/builtin/builtin_list.h
:
Application specific information and start-up requirements
Registration of Built-In Applications.
The NuttX build occurs in several phases as different build targets are executed:
(1) context when the configuration is established,
(2) depend when target dependencies are generated, and
(3) default (all
) when the normal compilation and link operations are performed.
Built-in application information is collected during the make context build phase.
An example application that can be "built-in" is be found in the apps/examples/hello directory
.
Let's walk through this specific cause to illustrate the general way that built-in applications are created and how they register themselves so that they can be used from NSH.
apps/examples/hello
.
The main routine for apps/examples/hello can be found in apps/examples/hello/main.c
.
The main routine is:
int hello_main(int argc, char *argv[]) { printf("Hello, World!!\n"); return 0; }
This is the built in function that will be registered during the context build phase of the NuttX build.
That registration is performed by logic in apps/examples/hello/Makefile
.
But the build system gets to that logic through a rather tortuous path:
The top-level context make target is in nuttx/Makefile
.
All build targets depend upon the context build target.
For the apps/
directory, this build target will execute the context target in the apps/Makefile
.
The apps/Makefile
will, in turn, execute the context targets in all of the configured sub-directories.
In our case will include the Makefile
in apps/examples
.
And finally, the apps/examples/Makefile
will execute the context target in all configured example
sub-directories, getting us finally to apps/examples/Makefile
which is covered below.
NOTE: Since this context build phase can only be executed one time, any subsequent configuration changes that you make will, then, not be reflected in the build sequence. That is a common area of confusion. Before you can instantiate the new configuration, you have to first get rid of the old configuration. The most drastic way to this is:
make distclean
But then you will have to re-configuration NuttX from scratch.
But if you only want to re-build the configuration in the apps/
sub-directory, then there is a less labor-intensive way to do that.
The following NuttX make command will remove the configuration only from the apps/
directory and will let you continue without re-configuring everything:
make apps_distclean
Logic for the context
target in apps/examples/hello/Makefile
registers the hello_main()
application in the builtin
's builtin_proto.h
and builtin_list.h
files.
That logic that does that in apps/examples/hello/Makefile
is abstracted below:
First, the Makefile
includes apps/Make.defs
:
include $(APPDIR)/Make.defs
This defines a macro called REGISTER
that adds data to the builtin header files:
define REGISTER @echo "Register: $1" @echo "{ \"$1\", $2, $3, $4 }," >> "$(APPDIR)/builtin/builtin_list.h" @echo "EXTERN int $4(int argc, char *argv[]);" >> "$(APPDIR)/builtin/builtin_proto.h" endef
When this macro runs, you will see the output in the build "Register: hello
", that is a sure sign that the registration was successful.
The make file then defines the application name (hello
), the task priority (default), and the stack size that will be allocated in the task runs (2K).
APPNAME = hello PRIORITY = SCHED_PRIORITY_DEFAULT STACKSIZE = 2048
And finally, the Makefile
invokes the REGISTER
macro to added the hello_main()
builtin application.
Then, when the system build completes, the hello
command can be executed from the NSH command line.
When the hello
command is executed, it will start the task with entry point hello_main()
with the default priority and with a stack size of 2K.
context: $(call REGISTER,$(APPNAME),$(PRIORITY),$(STACKSIZE),$(APPNAME)_main)
Other Uses of Built-In Application. The primary purpose of builtin applications is to support command line execution of applications from NSH. However, there is one other use of builtin applications that should be mentioned.
binfs.
binfs is a tiny file system located at apps/builtin/binfs.c
.
This provides an alternative what of visualizing installed builtin applications.
Without binfs, you can see the installed builtin applications using the NSH help command.
binfs will create a tiny pseudo-file system mounted at /bin
.
Using binfs, you can see the available builtin applications by listing the contents of /bin
directory.
This gives some superficial Unix compatibility, but does not really add any new functionality.
By default, built-in commands started from the NSH command line will run asynchronously with NSH. If you want to force NSH to execute commands then wait for the command to execute, you can enable that feature by adding the following to the NuttX configuration file:
CONFIG_SCHED_WAITPID=y
This configuration option enables support for the standard waitpid()
RTOS interface.
When that interface is enabled, NSH will use it to wait, sleeping until the built-in application executes to completion.
Of course, even with CONFIG_SCHED_WAITPID=y
defined, specific applications can still be forced to run asynchronously by adding the ampersand (&) after the NSH command.
4.4 Customizing NSH Initialization |
Ways to Customize NSH Initialization. There are three ways to customize the NSH start-up behavior. Here they are presented in order of increasing difficulty:
You can extend the initialization logic in configs/stm3240g-eval/src/stm32_appinit.c
.
The logic there is called each time that NSH is started and is good place in particular for any device-related initialization.
You replace the sample code at apps/examples/nsh/nsh_main.c
with whatever start-up logic that you want.
NSH is a library at apps/nshlib
.
apps.examples/nsh
is just a tiny, example start-up function (CONFIG_USER_ENTRYPOINT
()) that that runs immediately and illustrates how to start NSH
If you want something else to run immediately then you can write your write your own custom CONFIG_USER_ENTRYPOINT
() function and then start other tasks from your custom CONFIG_USER_ENTRYPOINT
().
NSH also supports a start-up script that executed when NSH first runs. This mechanism has the advantage that the start-up script can contain any NSH commands and so can do a lot of work with very little coding. The disadvantage is that is is considerably more complex to create the start-up script. It is sufficiently complex that is deserves its own paragraph
First of all you should look at NSH Start-Up Script paragraph. Most everything you need to know can be found there. That information will be repeated and extended here for completeness.
NSH Start-Up Script.
NSH supports options to provide a start up script for NSH.
The start-up script contains any command support by NSH (i.e., that you see when you enter 'nsh> help').
In general this capability is enabled with CONFIG_NSH_ROMFSETC=y
, but has several other related configuration options as described with the NSH-specific configuration settings paragraph.
This capability also depends on:
CONFIG_DISABLE_MOUNTPOINT=n
.
If mount point support is disabled, then you cannot mount any file systems.
CONFIG_NFILE_DESCRIPTORS > 4
.
Of course you have to have file descriptions to use any thing in the file system.
CONFIG_FS_ROMFS
enabled.
This option enables ROMFS file system support.
Default Start-Up Behavior. The implementation that is provided is intended to provide great flexibility for the use of Start-Up files. This paragraph will discuss the general behavior when all of the configuration options are set to the default values.
In this default case, enabling CONFIG_NSH_ROMFSETC
will cause NSH to behave as follows at NSH start-up time:
NSH will create a read-only RAM disk (a ROM disk), containing a tiny ROMFS file system containing the following:
`--init.d/ `-- rcS
Where rcS
is the NSH start-up script.
NSH will then mount the ROMFS file system at /etc
, resulting in:
|--dev/ | `-- ram0 `--etc/ `--init.d/ `-- rcS
By default, the contents of rcS
script are:
# Create a RAMDISK and mount it at /tmp mkrd -m 1 -s 512 1024 mkfatfs /dev/ram1 mount -t vfat /dev/ram1 /tmp
NSH will execute the script at /etc/init.d/rcS
at start-up (before the first NSH prompt).
After execution of the script, the root FS will look like:
|--dev/ | |-- ram0 | `-- ram1 |--etc/ | `--init.d/ | `-- rcS `--tmp/
Example Configurations.
Here are some configurations that have CONFIG_NSH_ROMFSETC=y
in the NuttX configuration file.
They might provide useful examples:
configs/hymini-stm32v/nsh2
configs/ntosd-dm320/nsh
configs/sim/nsh
configs/sim/nsh2
configs/sim/nx
configs/sim/nx11
configs/sim/touchscreen
In most of these cases, the configuration sets up the default /etc/init.d/rcS
script.
The default script is here: apps/nshlib/rcS.template
.
(The funny values in the template like XXXMKRDMINORXXX
get replaced via sed
at build time).
This default configuration creates a ramdisk and mounts it at /tmp
as discussed above.
If that default behavior is not what you want, then you can provide your own custom rcS
script by defining CONFIG_NSH_ARCHROMFS=y
in the configuration file.
Modifying the ROMFS Image.
The contents of the /etc
directory are retained in the file apps/nshlib/nsh_romfsimg.h
OR, if CONFIG_NSH_ARCHROMFS
is defined, include/arch/board/nsh_romfsimg.h
.
In order to modify the start-up behavior, there are three things to study:
Configuration Options.
The additional CONFIG_NSH_ROMFSETC
configuration options discussed with the other NSH-specific configuration settings.
tools/mkromfsimg.sh
Script.
The script tools/mkromfsimg.sh
creates nsh_romfsimg.h
.
It is not automatically executed.
If you want to change the configuration settings associated with creating and mounting the /tmp
directory, then it will be necessary to re-generate this header file using the tools/mkromfsimg.sh
script.
The behavior of this script depends upon several things:
The configuration settings then installed configuration.
The genromfs
tool(available from http://romfs.sourceforge.net) or included within the NuttX buildroot toolchain.
There is also a snapshot available in the NuttX tools repository here.
The xxd
tool that is used to generate the C header files (xxd is a normal part of a complete Linux or Cygwin installation, usually as part of the vi
package).
The file apps/nshlib/rcS.template
(OR, if CONFIG_NSH_ARCHROMFS
is defined include/arch/board/rcs.template
.
rcS.template
.
The file apps/nshlib/rcS.template
contains the general form of the rcS
file; configured values are plugged into this template file to produce the final rcS
file.
To generate a custom rcS
file a copy of rcS.template
needs to be placed at tools/
and changed according to the desired start-up behaviour.
Running tools/mkromfsimg.h
creates nsh_romfsimg.h
which needs to be copied to apps/nshlib
OR if CONFIG_NSH_ARCHROMFS
is defined to configs/<board>/include
.
rcS.template
.
The default rcS.template
, apps/nshlib/rcS.template
, generates the standard, default apps/nshlib/nsh_romfsimg.h
file.
If CONFIG_NSH_ARCHROMFS
is defined in the NuttX configuration file, then a custom, board-specific nsh_romfsimg.h
file residing in configs/<board>/include
will be used.
NOTE when the OS is configured, include/arch/board
will be linked to configs/<board>/include
.
All of the startup-behavior is contained in rcS.template
.
The role of mkromfsimg.sh
script is to (1) apply the specific configuration settings to rcS.template
to create the final rcS
, and (2) to generate the header file nsh_romfsimg.h
containing the ROMFS file system image.
To do this, mkromfsimg.sh
uses two tools that must be installed in your system:
The genromfs
tool that is used to generate the ROMFS file system image.
The xxd
tool that is used to create the C header file.
5.0 Shell Login |
5.1 Enabling Shell Logins |
NuttShell sessions can be protected by requiring that the user supply username and password credentials at the beginning of the session. Logins can be enabled for standard USB or serial consoles with:
CONFIG_NSH_CONSOLE_LOGIN=y
Logins for Telnet sessions can be enabled separately with:
CONFIG_NSH_TELNET_LOGIN=y
Logins can be enabled for either or both session types. On a successful login, the user will have access to the NSH session:
login: admin password: User Logged-in! NuttShell (NSH) nsh>
After each failed login attempt, a delay can be set up. The purpose of this delay is to discourage attempts to crack the password by brute force. That delay is configured with
CONFIG_NSH_LOGIN_FAILDELAY=0
This setting provides the login failure delay in units of milliseconds. The system will pause this amount of time after each failed login attempt. After a certain number of failed login attempts, the session will be closed. That number is controlled by:
CONFIG_NSH_LOGIN_FAILCOUNT=3
5.2 Verification of Credentials |
There are three ways that NSH can be configured to verify user credentials at login time:
The simplest implementation simply uses fixed login credentials and is selected with:
CONFIG_NSH_LOGIN_FIXED=y
The fixed login credentials are selected via:
CONFIG_NSH_LOGIN_USERNAME=admin CONFIG_NSH_LOGIN_PASSWORD="Administrator"
This is not very flexible since there can be only one user and the password is fixed in the FLASH image. This option is also not very secure because a malicious user could get the password by just looking at the .text
stings in the flash image.
NSH can also be configured to defer the entire user credential verification to platform-specific logic with this setting:
CONFIG_NSH_LOGIN_PLATFORM=y
In this case, NSH will call a platform-specific function to perform the verification of user credentials. The platform-specific logic must provide a function with the following prototype:
int platform_user_verify(FAR const char *username, FAR const char *password);
which is prototyped an described in apps/include/nsh.h
and which may be included like:
#include <apps/nsh.h>
An appropriate place to implement this function might be in the directory apps/platform/<board>
.
A final option is to use a password file contained encrypted password information. This final option is selected with the following and described in more detail in the following paragraph.
CONFIG_NSH_LOGIN_PASSWD=y
5.3 Password Files |
NuttX can also be configured to support a password file, by default at /etc/passwd
.
This option enables support for a password file:
CONFIG_NSH_LOGIN_PASSWD=y
This options requires that you have selected CONFIG_FSUTILS_PASSWD=y
to enable the access methods of apps/fsutils/passwd
:
CONFIG_FSUTILS_PASSWD=y
And this determines the location of the password file in a mounted volume:
CONFIG_FSUTILS_PASSWD_PATH="/etc/passwd"
/etc/passwd
is a standard location, but you will need to locate the password where ever you have a mounted volume.
The password file can be a fixed list of users in a ROMFS file system or a modifiable list maintained in a file in some writable file system. If the password file lies in a read-only file system like ROMFS, then you should also indicate that the password file is read-only.
CONFIG_FSUTILS_PASSWD_READONLY=y
If the password file is writable, then additional NSH commands will be enabled to modify the password file: useradd
, userdel
, and passwd
. If you do not wish you have these commands available, then they should be specifically disabled.
The password file logic requires a few additional settings:
The size of dynamically allocated and freed buffer that is used for file access:
CONFIG_FSUTILS_PASSWD_IOBUFFER_SIZE=512
And the 128-bit encryption key. The password file currently uses the Tiny Encryption Algorithm (TEA), but could be extended to use something more powerful.
CONFIG_FSUTILS_PASSWD_KEY1=0x12345678 CONFIG_FSUTILS_PASSWD_KEY2=0x9abcdef0 CONFIG_FSUTILS_PASSWD_KEY3=0x12345678 CONFIG_FSUTILS_PASSWD_KEY4=0x9abcdef0
Password can only be decrypted with access to this key. Note that this key could potentially be fished out of your FLASH image, but without any symbolic information, that would be a difficult job since the TEA KEY is binary data and not distinguishable from other binary data in the FLASH image.
If the password file is enabled (CONFIG_NSH_LOGIN_PASSWD=y
), then the fixed user credentials will not be used for the NSH session login. Instead, the password file will be consulted to verify the user credentials.
5.4 Creating a Password File for a ROMFS File System |
What we want to accomplish is a ROMFS file system, mounted at /etc
and containing the password file, passwd
like:
NuttShell (NSH) nsh> ls -Rl /etc /etc: dr-xr-xr-x 0 . dr-xr-xr-x 0 init.d/ -r--r--r-- 39 passwd /etc/init.d: dr-xr-xr-x 0 .. -r--r--r-- 110 rcS nsh>
Where /etc/init.d/rcS
is the start-up script; /etc/passwd
is a the password file. Note that here we assume that you are already using a start-up script. We can then piggyback the passwd file into the /etc
file system already mounted for the NSH start up file as described above above.
I use the sim/nsh configuration to create a new password file, but other configurations could also be used. That configuration already supports a ROMFS file system, passwords, and login prompts. First, I make these changes to that configuration.
Disable logins
- CONFIG_NSH_CONSOLE_LOGIN=y + # CONFIG_NSH_CONSOLE_LOGIN is not set # CONFIG_NSH_TELNET_LOGIN is not set
Move the password file to a write-able file system:
- CONFIG_FSUTILS_PASSWD_PATH="/etc/passwd" + CONFIG_FSUTILS_PASSWD_PATH="/tmp/passwd"
Make the password file modifiable
- CONFIG_FSUTILS_PASSWD_READONLY=y # CONFIG_FSUTILS_PASSWD_READONLY is not set
Now rebuild the simulation. No login should be required to enter the
shell and you should find the useradd
, userdel
, and passwd
commands available in the help summary, provided that they are enabled.
Make certain that the useradd
command is not disabled:
# CONFIG_NSH_DISABLE_USERADD is not set
Use the NSH useradd
command to add new uses with new user passwords like:
nsh> useradd <username> <password>
Do this as many times as you would like. Each time that you do this a new
entry with an encrypted password will be added to the passwd
file at
/tmp/passwd
. You can see the content of the password file like:
nsh> cat /tmp/passwd
When you are finished, you can simply copy the /tmp/passwd
content from the
cat
command and paste it into an editor. Make sure to remove any
carriage returns that may have ended up on the file if you are using
Windows.
Then create/re-create the nsh_romfsimg.h
file as described below.
The content on the nsh_romfsimg.h
header file is generated from a template directory structure. Create the directory structure:
mkdir etc mkdir etc/init.d
And copy your existing startup script into etc/init.c
as rcS
.
Save your new password file in the etc/
directory as passwd
.
Create the new ROMFS image.
genromfs -f romfs_img -d etc -V MyVolName
Convert the ROMFS image to a C header file
xxd -i romfs_img >nsh_romfsimg.h
Edit nsh_romfsimg.h
: Mark both data definitions as const
so that the data will be stored in FLASH.
Edit nsh_romfsimg.h, mark both data definitions as const
so that that will be stored in FLASH.
There is a good example of how to do this in the NSH simulation configuration at configs/sim/nsh. The ROMFS support files are provided at configs/sim/include and the README.txt file at the location provides detailed information about creating and modifying the ROMFS file system.
Index |