In order to write some little script for example.
Sure. You need to jailbreak it and install MobileTerminal (an application you'll find in Cydia for installation, once having jailbroken your iPhone).
MobileTerminal gives you access to the iPhones bash (shell).
To write decent shell scripts you would also need to install some shell utilities that you would expect to be there by default like vi, curl, openssh, ...
All of this is available in Cydia as well.
If you mean that you want to run shell commands on the iphone itself, you won't be able to do that without jailbreaking it first. Once jailbroken, there are many tools available for all kinds of "hacking".
My understanding is that jailbreaking is not illegal (by law) but not allowed by Apple (voids warranty?).